如何在 React Apollo 中让输入更加 DRY?

问题描述 投票:0回答:2

如何在 GQL Apollo React 中重用变量参数?例如在输入相同但我们需要对应不同情况的不同数据的情况下。

有没有办法在此查询调用的内部或外部定义它?

const REQUEST_1 = gql`
  query QueryA(
    $page: Int
    $a: String
    $b: Number
    $etc: EtcFilter
  ) {
    getData(
      limit: 24
      page: $page
      a: $a
      b: $b
      etc: $etc
    ) {
      total
      result {
        id
        time
        location
      }
    }
  }
  `
const REQUEST_2 = gql`
  query QueryA(
    $page: Int
    $a: String
    $b: Number
    $etc: EtcFilter
  ) {
    getData(
      limit: 24
      page: $page
      a: $a
      b: $b
      etc: $etc
    ) {
      total
      result {
        postContent
        date
        coordinates
        id
      }
    }
  }
  `

apollo-client react-apollo
2个回答
1
投票

根据您的查询示例,简短/悲伤的答案是您不能这样做

根据当前 GraphQL 规范

变量必须在操作的顶部定义,并且在 that 操作的整个执行过程中都在范围内。

该操作指的是查询/突变,在您的示例中,

REQUEST_1
REQUEST_2
是两个单独的操作。


graphql-specs 中存在一个未解决的问题,可能会解决此用例,但它还远未实现。


编辑一个操作示例(摘自评论)

您可以将这两种操作合并为一个,如下所示:

const REQUEST = gql`
  query QueryA(
    $page: Int
    $a: String
    $b: Number
    $etc: EtcFilter
  ) {
    getData(
      limit: 24
      page: $page
      a: $a
      b: $b
      etc: $etc
    ) {
      total
      result1: result {
        id
        time
        location
      }
      result2: result {
        postContent
        date
        coordinates
        id
      }
    }
  }
  `

因为您将使用不同的字段查询相同的

result
对象,所以您必须为其提供 别名

这当然会每次都进行完整查询,但它会保持输入参数更清晰。


0
投票

您可以尝试使用 Fragments:

const result1 = gql`
    fragment ResultFields on PaginationResult {
      id
      time
      location
    }
`;

const result2 = gql`
    fragment ResultFields on PaginationResult {
      postContent
      date
      coordinates
      id
    }
`;

const query = `query QueryA(
    $page: Int
    $a: String
    $b: Number
    $etc: EtcFilter
  ) {
    getData(
      limit: 24
      page: $page
      a: $a
      b: $b
      etc: $etc
    ) {
      total
      result {
        ...ResultFields
      }
    }
  }`

const REQUEST_1 = gql`${query}${result1}`
const REQUEST_2 = gql`${query}${result2}`

我编了类型

PaginationResult
,这取决于结果的类型。

不能 100% 确定上述内容是否适用于您的情况,但您可以在此处找到更多信息:https://www.apollographql.com/docs/react/data/fragments/

© www.soinside.com 2019 - 2024. All rights reserved.