【问题标题】:How to send one-off query with Relay?如何使用 Relay 发送一次性查询?
【发布时间】:2018-04-13 23:56:54
【问题描述】:

我正在尝试使用 Relay 发送一次性查询。所以,我不一定想使用QueryRenderer,而是有一个简单的 API 来发送查询而不将结果绑定到 React 组件。

以前,这可以通过network 上的fetch 方法实现:

const checkVoteQueryText = `
  query CheckVoteQuery($userId: ID!, $linkId: ID!) {
    viewer {
      allVotes(filter: {
        user: { id: $userId },
        link: { id: $linkId }
      }) {
        edges {
          node {
            id
          }
        }
      }
    }
  }`
const checkVoteQuery = { text: checkVoteQueryText }
const result = await this.props.relay.environment._network.fetch(checkVoteQuery, {userId, linkId})

然而,fetch 似乎在一些较新版本的 Relay 中已被弃用。现在有没有可以使用的替代品?

如果 Relay 不允许一次性查询,我可能只需要 graphql-request 或纯 JS 获取来完成工作。但是能够为此使用 Relay 会很好,因为它已经知道我的端点。

【问题讨论】:

    标签: javascript reactjs graphql relayjs


    【解决方案1】:

    啊,这实际上很容易实现。事实上,在this.props.relay.environment._network 上调用fetch 只是重用了在创建时传递给Network 的函数。所以,可以重用这个函数,在我的例子中它被称为fetchQuery

    Environment.js

    import {GC_AUTH_TOKEN} from './constants'
    import { SubscriptionClient } from 'subscriptions-transport-ws'
    
    const {
      Environment,
      Network,
      RecordSource,
      Store,
    } = require('relay-runtime')
    
    const store = new Store(new RecordSource())
    
    // Export it here so it can be reused in other files
    export const fetchQuery = (operation, variables) => {
      return fetch('https://api.graph.cool/relay/v1/cj9h5g99s24fb0100nsp81d4y', {
        method: 'POST',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${localStorage.getItem(GC_AUTH_TOKEN)}`
        },
        body: JSON.stringify({
          query: operation.text,
          variables,
        }),
      }).then(response => {
        return response.json()
      })
    }
    
    const network = Network.create(fetchQuery)
    
    const environment = new Environment({
      network,
      store,
    })
    
    export default environm
    

    ent

    【讨论】:

      猜你喜欢
      • 2016-03-07
      • 1970-01-01
      • 2015-11-27
      • 2021-11-30
      • 1970-01-01
      • 2020-06-12
      • 2019-06-10
      • 1970-01-01
      • 2015-04-08
      相关资源
      最近更新 更多