【问题标题】:How to implement networkinteface middleware for apollo client in react-native如何在 react-native 中为 apollo 客户端实现网络接口中间件
【发布时间】:2017-04-06 20:59:13
【问题描述】:

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

【问题讨论】:

    标签: apollostack react-apollo


    【解决方案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()
      },
    }])
    

    【讨论】:

      猜你喜欢
      • 2021-01-11
      • 2020-03-05
      • 2018-04-02
      • 2020-06-21
      • 1970-01-01
      • 2020-10-23
      • 2019-03-17
      • 1970-01-01
      • 2020-09-20
      相关资源
      最近更新 更多