我需要使用apollo在native native中实现登录,并想知道
a)如何从客户端网络接口替换或删除中间件。我不应该直接访问_middlewares属性吗?我看到一种推送middlware的use
方法,但是没有办法删除。
b)如果我们想将示例从localstorage更改为asyncstorage,我们是否应该直接从redux存储读取网络接口?最好的方法是什么?
// in src/index.js
const networkInterface = createNetworkInterface({ uri: 'https://api.graph.cool/simple/v1/__PROJECT_ID__' })
networkInterface.use([{
applyMiddleware (req, next) {
if (!req.options.headers) {
req.options.headers = {}
}
// change this from localstorage to asyncstorage, or perhaps redux store
if (localStorage.getItem('auth0IdToken')) {
req.options.headers.authorization = `Bearer ${localStorage.getItem('auth0IdToken')}`
}
next()
},
}])
答案 0 :(得分:1)
a)此时(apollo-client@0.6.0)无法删除连接到NetworkInterface的中间件。
b)您可以使用以下架构:
// in src/index.js
const networkInterface = createNetworkInterface({ uri: 'https://api.graph.cool/simple/v1/__PROJECT_ID__' })
// structure of auth reducer:
// auth: {
// token: "xyz"
// }
//create redux's store before using of middleware
const store: Store<any> = createStore(combineReducers({
auth = authReducer
})
networkInterface.use([{
applyMiddleware (req, next) {
const tokenFromReduxStore = store.getState().auth.token;
if (!req.options.headers) {
req.options.headers = {}
}
// change this from localstorage to asyncstorage, or perhaps redux store
if (tokenFromReduxStore) {
req.options.headers.authorization = tokenFromReduxStore
}
next()
},
}])