GraphQL错误“字段必须是具有字段名称作为键的对象或返回此类对象的函数。”

Jaz*_*zzy 5 javascript node.js graphql graphql-js

为什么我从架构文件中收到此错误?

错误:

graphql/jsutils/invariant.js:19
throw new Error(message);
^

Error: Entity fields must be an object with field names as keys or a     function which returns such an object.
Run Code Online (Sandbox Code Playgroud)

错误围绕着entity支柱PersonType。msg指示上的每个字段Entity都应该是一个对象,但是我在任何地方都没有看到这样的示例。

基本上,我试图基于Person查询返回的值从DuckDuckGo API中获取一些数据。从API返回的数据是一个具有许多属性的对象,我试图使用其中的两个来entity在我的对象上填充一个Person对象。

我看过类型系统文档,但看不到答案。http://graphql.org/docs/api-reference-type-system/

这是在Node上运行并提供给GraphiQL UI的代码。

任何建议,将不胜感激!谢谢。

码:

const PersonType = new GraphQLObjectType({
name: 'Person',
description: '...',

fields: () => ({
    name: {
        type: GraphQLString,
        resolve: (person) => person.name
    },
    url: {
        type: GraphQLString,
        resolve: (person) => person.url
    },
    films: {
        type: new GraphQLList(FilmType),
        resolve: (person) => person.films.map(getEntityByURL)
    },
    vehicles: {
        type: new GraphQLList(VehicleType),
        resolve: (person) => person.vehicles.map(getEntityByURL)
    },
    species: {
        type: new GraphQLList(SpeciesType),
        resolve: (person) => person.species.map(getEntityByURL)
    },
    entity: {
        type: new GraphQLObjectType(EntityType),
        resolve: (person) => getEntityByName(person.name)
    }
})
});

const EntityType = new GraphQLObjectType({
name: 'Entity',
description: '...',

fields: () => ({
    abstract: {
        type: GraphQLString,
        resolve: (entity) => entity.Abstract
    },
    image: {
        type: GraphQLString,
        resolve: (entity) => entity.Image
    }
})
});



function getEntityByName(name) {
    return fetch(`${DDG_URL}${name}`)
    .then(res => res.json())
    .then(json => json);
}
Run Code Online (Sandbox Code Playgroud)

更新 这是我所指的给出问题的代码:

entity: {
        type: EntityType, // <- no need to wrap this in GraphQLObjectType
        resolve: (person) => getEntityByName(person.name)
    }
Run Code Online (Sandbox Code Playgroud)

Jaz*_*zzy 5

EntityType已定义为GraphQLObjectType. 所以,没有必要包裹GraphQLObjectType周围EntityType一次。

更改entity字段PersonType如下:

    entity: {
        type: EntityType, // <-- Duh!
        resolve: (person) => getEntityByName(person.name)
    }
Run Code Online (Sandbox Code Playgroud)

  • 这不是一个很好的答案,只是因为该问题没有显示答案实际引用的代码块,使其无法为其他人效仿。可悲的是,也是谷歌上的最佳答案。 (10认同)
  • 对于后面的人,我回答了我自己的问题。我在答案中提到的代码在问题中。请看更新。 (2认同)