首页 > 解决方案 > Graphql data modeling: extending types and interfaces

问题描述

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.

标签: graphql

解决方案


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.


推荐阅读