Using GraphQL Fragment on multiple types

后端 未结 2 556
迷失自我
迷失自我 2021-01-07 18:42

If I have a set of field that is common to multiple types in my GraphQL schema, is there a way to do something like this?

type Address {
  line1: String
  ci         


        
相关标签:
2条回答
  • 2021-01-07 19:16

    Fragments are only used on the client-side when making requests -- they can't be used inside your schema. GraphQL does not support type inheritance or any other mechanism that would reduce the redundancy of having to write out the same fields for different types.

    If you're using apollo-server, the type definitions that make up your schema are just a string, so you can implement the functionality you're looking for through template literals:

    const nameAndAddress = `
      name: String
      address: Address
    `
    
    const typeDefs = `
      type Business {
         ${nameAndAddress}
         hours: String
      }
    
      type Customer {
         ${nameAndAddress}
         customerSince: Date
      }
    `
    

    Alternatively, there are libraries out there, like graphql-s2s, that allow you to use type inheritance.

    0 讨论(0)
  • 2021-01-07 19:17

    Don't know if it was not available at this question time, but I guess interfaces should fit your needs

    0 讨论(0)
提交回复
热议问题