仅在用户验证后如何设置Apollo客户端? [英] How to set up Apollo client only after user authenticates?
问题描述
在用户验证/登录之前不建立连接的情况下,我对如何构建React/GraphQL(Apollo)应用程序感到有些困惑.
I'm a bit confused on how to structure my React/GraphQL (Apollo) app when no connection should be made until the user authenticates/logs in.
目前我有这个:
class App extends Component {
render() {
return (
<ApolloProvider client={client}>
<Provider store={store}>
<Router>
<div>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/login">Log In</Link></li>
<li><Link to="/signup">Sign Up</Link></li>
</ul>
<AuthenticatedRoute exact path="/" component={HomePage} />
<Route path="/login" component={LoginPage} />
<Route path="/signup" component={SignupPage} />
</div>
</Router>
</Provider>
</ApolloProvider>
);
}
}
这是网络接口的创建:
const networkInterface = createNetworkInterface({
uri: process.env.NODE_ENV === 'development'
? 'http://localhost:3000/graphql'
: 'TBD',
});
networkInterface.use([
{
applyMiddleware(req, next) {
if (!req.options.headers) {
req.options.headers = {}; // Create the header object if needed.
}
getUserSession()
.then(session => {
// get the authentication token from local storage if it exists
// ID token!
req.options.headers.authorization = session
.getIdToken()
.getJwtToken();
})
.catch(err => {
console.error('oh, this is bad');
})
.then(next);
},
},
]);
如何组织此操作,以便仅在用户通过身份验证之后才初始化和设置一次 Apollo客户端?
How do I organize this so that the Apollo client is only initialized and set up once, and only after the user has authenticated?
我想知道是否可以使用 withApollo 来访问客户直接完成GraphQL身份验证和这样连接.
I'm wondering if I could use withApollo to somehow access the client directly and complete the GraphQL auth & connection that way.
使用Redux跟踪用户状态,将App
换成connect
.当用户进行身份验证时,这将触发Redux状态更改,从而触发App
的componentDidUpdate
,该更改可能会创建Apollo的网络接口,从而导致在App
中进行重新渲染,从而将授权的client
传递到
Use Redux to track user state, wrap App
with connect
. When the user authenticates, this triggers a Redux state change which triggers App
's componentDidUpdate
which could create the network interface for Apollo, causing a re-render in App
which would pass an authorized client
into <ApolloProvider client={client}>
.
推荐答案
我使用ApolloClient示例 http://dev.apollodata.com/react/auth.html#Header
I use ApolloClient example http://dev.apollodata.com/react/auth.html#Header
networkInterface.use([{
applyMiddleware(req, next) {
if (!req.options.headers) {
req.options.headers = {}; // Create the header object if needed.
}
// get the authentication token from local storage if it exists
const token = localStorage.getItem('token');
req.options.headers.authorization = token ? `Bearer ${token}` : null;
next();
}
}])
块applyMiddleware
将始终在获取到GraphQL服务器之前运行,因此您只需要在登录时设置localStorage
并在注销时删除.
the block applyMiddleware
will always run before fetching to GraphQL server, so you just need to set localStorage
when login and delete when logout.
这篇关于仅在用户验证后如何设置Apollo客户端?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!