Using GraphQL Fragment on multiple types

只谈情不闲聊 提交于 2019-11-28 07:07:22

问题


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
  city: String
  state: String 
  zip: String
}

fragment NameAndAddress on Person, Business {
  name: String
  address: Address
}

type Business {
   ...NameAndAddress
   hours: String
}

type Customer {
   ...NameAndAddress
   customerSince: Date
}

回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/48940240/using-graphql-fragment-on-multiple-types

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!