0

我需要使用 apollo 在 react native 中实现登录,并且想知道

a) 如何从客户端网络接口中替换或删除中间件。我不应该直接访问 _middlewares 属性吗?我看到了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()
  },
}])
4

1 回答 1

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()
  },
}])
于 2017-01-26T18:20:39.983 回答