【问题标题】:Reusing Group of Fields in GraphQL Schema在 GraphQL Schema 中重用字段组
【发布时间】:2023-03-31 10:56:02
【问题描述】:

我有一组特定的 GraphQL 字段,我想在一堆不同的类型中重复使用它们。

当前的类型是这样的,和我的分页信息有关:

  type Pagination {
    totalDocs: Int!
    limit: Int!
    totalPages: Int!
    page: Int!
    offset: Int!
    pagingCounter: Int!
    hasPrevPage: Boolean!
    hasNextPage: Boolean!
    prevPage: Int
    nextPage: Int
  }

有几种类型应包含此信息。我知道我可以将信息嵌套在一个子字段中,然后让该子字段指向这种类型。像这样:

type House {
    cost: Int!
    size: Int!
    pagination: Pagination
}

但是,如果可能的话,我宁愿不嵌套信息。例如,完成的类型可能看起来

type House {
    cost: Int!
    size: Int!
    totalDocs: Int!
    limit: Int!
    totalPages: Int!
    page: Int!
    offset: Int!
    pagingCounter: Int!
    hasPrevPage: Boolean!
    hasNextPage: Boolean!
    prevPage: Int
    nextPage: Int
  }


type Car {
    speed: Int!
    color: String!
    totalDocs: Int!
    limit: Int!
    totalPages: Int!
    page: Int!
    offset: Int!
    pagingCounter: Int!
    hasPrevPage: Boolean!
    hasNextPage: Boolean!
    prevPage: Int
    nextPage: Int
  }

是否可以将重复字段提取到另一个公共块中并在多种类型之间共享,而无需将数据嵌套在另一个字段中。例如,对于对象,使用扩展 (...) 运算符也可以实现类似的操作。

这样的?

type Car {
        cost: Int!
        size: Int!
        ...pagination
      }

【问题讨论】:

  • 您可以创建一个包含所有字段的界面。然后当你创建新类型时,你需要实现所有字段的接口,你仍然需要编写所有字段,但是当一个字段丢失时它会报错

标签: javascript graphql


【解决方案1】:

如果您使用 gql 标记或其他一些基于字符串的系统来形成它们,您可以将它们抽象成一个通用类型并以模板文字形式将它们放入。


const Pagination = `
    totalDocs: Int!
    limit: Int!
    totalPages: Int!
    page: Int!
    offset: Int!
    pagingCounter: Int!
    hasPrevPage: Boolean!
    hasNextPage: Boolean!
    prevPage: Int
    nextPage: Int
`;

module.exports = `
  type Car {
    cost: Int!
    size: Int!
    ${Pagination}
  }

  type House {
    cost: Int!
    size: Int!
    ${Pagination}
  }
`;

【讨论】:

    猜你喜欢
    • 2016-03-03
    • 2019-12-14
    • 2019-02-15
    • 1970-01-01
    • 2016-12-05
    • 2018-09-07
    • 2015-01-29
    • 2019-12-09
    • 2019-09-28
    相关资源
    最近更新 更多