【问题标题】:Apollo-client custom network interface to make different gql queries when offline/online?Apollo-client 自定义网络接口在离线/在线时进行不同的 gql 查询?
【发布时间】:2018-01-23 11:01:32
【问题描述】:

我正在开发一个离线优先的 Expo/React Native 应用程序,使用 GraphQL + Apollo Client + Join Monster,并将数据存储在 sqlite db 客户端。

我的架构(以及其余代码)看起来与 https://github.com/tslater/reactnative-relay-offline/blob/master/graphql/relay-schema/index.js 非常相似,除了我使用 Apollo Client 作为我的 GraphQL 客户端,而不是使用 Relay。

我有一个自定义网络接口,如下所示:

import schema from './graphql/relay-schema'

class LocalNetworkInterface implements NetworkInterface {
  constructor(schema) {
    this.schema = schema
  }
  query(request) {
    const { query, variables } = request
    return graphql(
      this.schema,
      printAST(query),
      null,
      null,
      variables,
    )
  }
  getSchema() {
    return this.schema
  }
}

export function createLocalNetworkInterface(options) {
  const { schema } = options
  return new LocalNetworkInterface(schema)
}

const networkInterface = createLocalNetworkInterface({ schema })
const client = new ApolloClient({networkInterface})

这适用于离线查询。

但是,我不确定如何调整它以便能够在应用检测到它具有互联网连接时对真实服务器进行查询。如果这很重要,我将对服务器发出的 gql 查询与我对本地数据库发出的查询略有不同。 https://github.com/apollographql/apollo-link 在这里有用吗?

【问题讨论】:

    标签: react-native offline graphql react-apollo apollo-client


    【解决方案1】:

    我从 Apollo Data 中找到了一些很好的文档来解决这个问题,http://dev.apollodata.com/core/network.html#CustomNetworkInterfaceExample

    我将它与react-native-offline 包结合起来得到一个isConnected 道具,我可以将它与我的query variables 一起传递,并创建了一个新的HybridNetworkInterface

    import {createNetworkInterface} from 'apollo-client'
    import {createLocalNetworkInterface} from './LocalNetworkInterface'
    
    export class HybridNetworkInterface {
      constructor(opts) {
        this.localInterface = createLocalNetworkInterface(opts)
        this.networkInterface = createNetworkInterface(opts) // createNetworkInterface
      }
      query(request) {
        if (request.variables && request.variables.isConnected) {
          return this.networkInterface.query(request)
        }
        return this.localInterface.query(request)
      }
      use(middlewares) {
        this.networkInterface.use(middlewares)
        this.localInterface.use(middlewares)
        return this
      }
      useAfter(afterwares) {
        this.networkInterface.useAfter(afterwares)
        this.localInterface.useAfter(afterwares)
        return this
      }
    }
    
    export function createHybridNetworkInterface(opts) {
      return new HybridNetworkInterface(opts)
    }
    

    【讨论】:

      猜你喜欢
      • 2020-06-07
      • 2020-01-06
      • 2019-02-10
      • 2018-03-04
      • 2020-10-18
      • 2016-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多