在多种类型上使用GraphQL Fragment [英] Using GraphQL Fragment on multiple types

查看:736
本文介绍了在多种类型上使用GraphQL Fragment的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我的GraphQL模式中有多个类型共有的一组字段,是否可以执行类似的操作?

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
}

推荐答案

片段仅在发出请求时在客户端使用-不能在架构内部使用. GraphQL不支持类型继承或任何其他机制,这些机制会减少必须为不同类型写出相同字段的冗余性.

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.

如果使用的是apollo-server,则构成架构的类型定义只是一个字符串,因此您可以通过模板文字实现所需的功能:

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

或者,还有一些库,例如 graphql-s2s ,您可以使用类型继承.

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

这篇关于在多种类型上使用GraphQL Fragment的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆