Graphql 数据建模:扩展类型和接口 [英] Graphql data modeling: extending types and interfaces

查看:13
本文介绍了Graphql 数据建模:扩展类型和接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个非常基本的问题,但如何调用扩展类型或接口?

所有文档都指向使用extend type Person来添加基于Person的字段.

我希望它像这样工作

Employee 扩展类型 Person {薪水:Int!}

但文档表明它是这样的:

扩展类型人{薪水:Int!}

那么,我如何查询员工工资?如果 Person 有多个扩展名怎么办,例如雇员和租客?我想我可能会受到传统思维的阻碍,但我希望扩展能够产生一些命名和可查询的东西.

解决方案

extend 关键字有效地用于修改模式中的现有类型.这在两种情况下最常用:

1.连接表示单个架构的多个字符串.您可以将架构分解为多个文件,并按域划分.然后,您可以执行以下操作:

#base.graphql类型查询{观众:用户}# 用户.graphql扩展类型查询{用户:[用户!]!}# post.graphql扩展类型查询{发帖:[发帖!]!}

这会产生一个实际上与以下相同的模式:

类型查询{观众:用户用户:[用户!]!发帖:[发帖!]!}

2.从基础架构扩展.您可能有多个构建在某个基础架构之上的架构.或者您可能正在将远程模式拼接在一起.在这些场景中,我们通常希望添加特定于我们的新架构的字段,而这些字段不存在于基本类型中.这也可用于实现基本架构中缺少的指令:

扩展类型 SomeType @customDirective

extend 关键字只能修改现有类型;它不是继承的工具.事实上,GraphQL 不支持类型继承.接口提供了对现有类型的抽象级别,但实现接口的类型不会从该接口继承任何字段.没有办法做到这一点,除非您使用诸如 graphql-s2s 之类的库.>

This is a very basic question but how do you call an extended type or interface?

All the documentations points to using extend type Person to add fields based on Person.

I would expect it to work like this

Employee extend type Person {
   salary: Int!
}

But the documentation suggests it's like this:

extend type Person{
   salary: Int!
}

So, how do I query for an Employee salary? What if there are multiple extensions of Person, e.g. Employee and Renter? I think I might be hampered by traditional thinking but I would expect the extension to result in something named and queryable.

解决方案

The extend keyword is effectively used to modify an existing type within a schema. This is most commonly used in two scenarios:

1. Concatenating multiple strings that represent a single schema. You can have your schema broken up across multiple files, divided by domain. You can then do something like:

#base.graphql
type Query {
  viewer: User
}

# user.graphql
extend type Query {
  users: [User!]!
}

# post.graphql
extend type Query {
  post: [Post!]!
}

This results in a schema that's effectively the same as:

type Query {
  viewer: User
  users: [User!]!
  post: [Post!]!
}

2. Extending from a base schema. You might have multiple schemas that build on top of some base schema. Or you might be stitching together remote schemas. In these scenarios, we often want to add fields specific to our new schema that don't exist on the base types. This can be used to implement directives that are missing from the base schema as well:

extend type SomeType @customDirective

The extend keyword can only modify existing types; it is not a vehicle for inheritance. In fact, GraphQL does not support type inheritance. Interfaces provide a level of abstraction over existing types, but types that implement an interface do not inherit any fields from that interface. There's no way to do that, unless you use some library like graphql-s2s.

这篇关于Graphql 数据建模:扩展类型和接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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