如何在GraphQL中扩展类型? [英] How do you extend types in GraphQL?

查看:64
本文介绍了如何在GraphQL中扩展类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如, 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:

对象类型扩展用于表示从某种原始类型扩展过来的类型.例如,它可能用于表示本地数据

Object type extensions are used to represent a type which has been extended from some original type. For example, this might be used to represent local data

在您的示例中,

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文档没有提及有关扩展的任何内容,但文档是毫无生气的,并且是不完全支持扩展,但是由于您已将问题标记为,您可以使用 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中扩展类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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