如何在react-native中为apollo客户端实现networkinteface中间件

时间:2016-11-23 01:18:01

标签: apollostack react-apollo

我需要使用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()
  },
}])

1 个答案:

答案 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()
  },
}])