问题描述
例如, Pet
是具有所有者
和名称
的动物
.
type Animal {
species: String
}
type Pet extends Animal {
owner: Owner
name: String
}
推荐答案
从 GraphQL规范的2018年6月稳定版本,一个对象类型可以扩展另一个对象类型:
Starting with the June2018 stable version of the GraphQL spec, an Object type can extend another Object type:
在您的示例中,
type Animal {
species: String
}
extend type Animal {
owner: Owner
name: String
}
这本身不是继承;您只能扩展基本类型,而不能基于该基本类型创建新类型.注意,新类型没有名称.现有的 Animal
类型得到扩展.
This isn't inheritance per se; you can only extend the base type, not create new types based on it. Note there is no name for the new type; the existing Animal
type is extended.
graphql.org文档没有提及有关扩展
的任何内容,但文档是毫无生气的,并且是从Facebook的所有权过渡到Linux基金会.JavaScript参考实现不完全支持扩展,但是由于您已将问题标记为apollo-server ,您可以使用 graphql-tools
,做:
The graphql.org documentation doesn't mention anything about extend
, but the documentation is admittedly lackluster and being transitioned from Facebook's ownership to the Linux Foundation.The JavaScript reference implementation doesn't fully support extensions, but since you've tagged your question apollo-server, you can use graphql-tools
, which does:
const { graphql } = require('graphql');
const { makeExecutableSchema } = require('graphql-tools');
const typeDefs = `
type Person {
name: String!
}
extend type Person {
salary: Int
}
type Query {
person: Person
}
`;
const resolvers = {
Query: {
person: () => ({ name: "John Doe", salary: 1234 })
}
}
const schema = makeExecutableSchema({ typeDefs, resolvers });
graphql(schema, '{ person {name salary} }').then((response) => {
console.log(response);
});
有关实际类型继承,请参见 graphql-s2s库.
For actual type inheritance, see the graphql-s2s library.
这篇关于如何在GraphQL中扩展类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!