重用GraphQL模式中的字段组

我有一组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
  }

Is it possible to extract the repetitive fields into another common chunk and share it across multiple types, without nesting the data inside of another field. With objects, for example, something similar would be possible with the spread (...) operator.

像这样吗

type Car {
        cost: Int!
        size: Int!
        ...pagination
      }
评论
  • rut
    rut 回复

    如果要使用gql标签或其他基于字符串的系统来构成它们,则可以将它们抽象为通用类型,并以Template-literal形式输入。

    
    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}
      }
    `;