GraphQL嵌套类型:“ ...的类型必须为Output Type,但得到:未定义。”

时间:2018-07-11 02:39:50

标签: graphql

我意识到这个问题也曾被类似的恶心问到,但我一直无法找到与我的情况相符的既存问题。我正在为pokeapi.co构建一个简单的GraphQL包装器,以学习GraphQL。一切都进行得很顺利,直到我尝试将一种类型嵌套在另一种类型中。

graphiql错误状态为“ pokemon.abilities的类型必须为Output Type,但得到:未定义。”

每个类型都需要特定的解析器吗? 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
}

1 个答案:

答案 0 :(得分:1)

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

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