graphql - 如何在 GraphQL buildSchema 中使用联合

标签 graphql graphql-js

以下是我使用 GraphQL 模式字符串创建模式并将其附加到我的 Express 服务器的方式:

var graphql = require('graphql');
var graphqlHTTP = require('express-graphql');
[...]
    return graphqlHTTP({
      schema: graphql.buildSchema(schemaText),
      rootValue: resolvers,
      graphiql: true,
    });

这是模块的所有非常基本的使用。在我想定义一个联合之前,它运行良好并且非常方便:
union MediaContents = Photo|Youtube

type Media {
  Id: String
  Type: String
  Contents: MediaContents
}

我发现无法完成这项工作,查询 Contents 完成了它必须做的事情,返回正确的对象但失败并显示消息 Generated Schema cannot use Interface or Union types for execution .

使用 buildSchema 时是否可以使用联合?

最佳答案

这正是我们创建 graphql-tools 的原因。包,就像 buildSchema 的生产就绪的增压版本: http://dev.apollodata.com/tools/graphql-tools/resolvers.html#Unions-and-interfaces

您可以通过提供 __resolveType 来简单地使用联合。联合上的方法,与 GraphQL.js 一样:

# Schema
union Vehicle = Airplane | Car

type Airplane {
  wingspan: Int
}

type Car {
  licensePlate: String
}

// Resolvers
const resolverMap = {
  Vehicle: {
    __resolveType(obj, context, info){
      if(obj.wingspan){
        return 'Airplane';
      }
      if(obj.licensePlate){
        return 'Car';
      }
      return null;
    },
  },
};

唯一的变化是,使用 makeExecutableSchema,而不是提供解析器作为根对象。 :
const graphqlTools = require('graphql-tools');
return graphqlHTTP({
  schema: graphqlTools.makeExecutableSchema({
    typeDefs: schemaText,
    resolvers: resolvers
  }),
  graphiql: true,
});

另请注意,解析器的签名将匹配常规 GraphQL.js 样式,因此它将是 (root, args, context)而不仅仅是 (args, context)这是您使用 rootValue 时得到的结果.

关于graphql - 如何在 GraphQL buildSchema 中使用联合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44246290/

相关文章:

node.js - 如何在 graphql 模式中迭代 json 嵌套数组

javascript - 如何在 graphQL 中对字段进行运行时数据操作?

javascript - TS编译器错误: Type 'string' is not assignable to type 'Status'

javascript - GraphQL 指定多种类型的数组

node.js - GraphQL:graphql 中嵌套对象类型的解析器

graphql - GraphQL 操作名称是否会改变查询行为?

javascript - React Apollo - 取消订阅查询

amazon-web-services - 使用 AWS AppSync 进行输入验证

javascript - 在 GraphQL 中的突变之前删除只读字段

javascript - 使用 graphql 模式语言的嵌套查询