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

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

问题描述

例如,Pet 是具有 ownernameAnimal.

For example, a Pet is an Animal with an owner and name.

type Animal {
  species: String
}

type Pet extends Animal {
  owner: Owner
  name: String
}

推荐答案

2018 年 6 月稳定版 GraphQL 规范,一个对象类型可以扩展另一个对象类型:

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 文档 没有提到任何关于 extend,但文档无可否认并且从 Facebook 的所有权过渡到 Linux 基金会.JavaScript 参考实现 不完全支持扩展,但由于你已经标记了你的问题 ,你可以使用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天全站免登陆