【问题标题】:GraphQL nested types: "The type of ... must be Output Type but got: undefined."GraphQL 嵌套类型:“......的类型必须是输出类型,但得到:未定义。”
【发布时间】:2018-12-18 23:05:39
【问题描述】:

我意识到这个问题已经被问到类似的问题,但我无法找到与我的情况相匹配的预先存在的问题。我正在为pokeapi.co 构建一个简单的 GraphQL 包装器来学习 GraphQL。一切都很顺利,直到我尝试将一种类型嵌套在另一种类型中。

graphiql 错误状态“pokemon.abilities 的类型必须是输出类型但得到:未定义。”

每种类型都需要特定的解析器吗? getPokemonById 解析器包含 Abilities 数组所需的数据。

此外,就项目结构而言,我(非常)松散地遵循this repo 以分离关注点。对结构的想法也非常开放。

types.js

const {
  GraphQLList,
  GraphQLObjectType,
  GraphQLString,
  GraphQLInt,
  GraphQLBoolean
} = require("graphql");

const AbilityType = new GraphQLObjectType({
  name: "ability",
  fields: {
    is_hidden: { type: GraphQLBoolean },
    slot: { type: GraphQLInt },
    ability: {
      name: { type: GraphQLString },
      url: { type: GraphQLString }
    }
  }
});

const PokemonType = new GraphQLObjectType({
  name: "pokemon",
  fields: {
    id: { type: GraphQLInt },
    name: { type: GraphQLString },
    base_experience: { type: GraphQLInt },
    height: { type: GraphQLInt },
    is_default: { type: GraphQLBoolean },
    order: { type: GraphQLInt },
    weight: { type: GraphQLInt },
    abilities: new GraphQLList(AbilityType),
  }
});

module.exports = {
  PokemonType,
  AbilityType,
};

queries.js

const { GraphQLInt, GraphQLObjectType } = require('graphql');
const { PokemonType } = require('../types/pokemon');
const { getPokemonById } = require("../resolvers/pokemon");

const pokemonQuery = new GraphQLObjectType({
  name: "Query",
  fields: {
    pokemon: {
      type: PokemonType,
      args: {
        id: { type: GraphQLInt }
      },
      resolve: (_, { id }) => {
        return getPokemonById(id);
      }
    }
  }
});

module.exports = {
  pokemonQuery
};

resolvers.js

const rp = require("request-promise");

const BASE_URL = "https://pokeapi.co/api/v2/pokemon";

const getPokemonById = id => {
  console.log(`attempting to query pokemon with id ${id}`)

  const rpOptions = {
    uri: `${BASE_URL}/${id}/`,
    headers: {
      'User-Agent': 'Request-Promise'
    },
    json: true,
  };
  return rp(rpOptions).catch(err => console.error(err));
}

module.exports = {
  getPokemonById
}

【问题讨论】:

    标签: graphql


    【解决方案1】:

    问题似乎出在PokemonType 下的abilities 文件中,它缺少类型定义。尝试将其更新为:

    const PokemonType = new GraphQLObjectType({
      name: "pokemon",
      fields: {
        ....
        order: { type: GraphQLInt },
        weight: { type: GraphQLInt },
        abilities: { type: new GraphQLList(AbilityType) },
      }
    });
    

    【讨论】:

    • 完整解决方案还需要在 AbilityType 中为 abilities.ability 嵌套一个 new GraphQLObjectType。谢谢,马可!
    猜你喜欢
    • 2018-06-30
    • 2019-12-23
    • 2017-08-16
    • 2019-09-19
    • 2018-11-18
    • 2018-06-25
    • 2016-10-14
    • 2016-06-29
    • 2017-12-12
    相关资源
    最近更新 更多