当参数为输入类型时,如何查询GraphQL模式?

时间:2019-09-10 19:26:29

标签: graphql

我对如何查询以下GraphQL模式感到困惑。我正尝试查询 pokemons 来获取搜索结果,但事实是PokemonQueryInput!在参数和PokemonConnection中被调用!结果使我感到困惑。 如何正确添加过滤器作为参数?以及如何正确利用PokemonConnection?


schema.graphql

    type Query {
        pokemons(query: PokemonsQueryInput!): PokemonConnection!
        pokemonByName(name: String!): Pokemon
        pokemonById(id: ID!): Pokemon
        pokemonTypes: [String!]!
    }

    input PokemonsQueryInput {
        limit: Int = 10
        offset: Int = 0
        search: String
        filter: PokemonFilterInput
    }

    input PokemonFilterInput {
        type: String
        isFavorite: Boolean
    }

    type PokemonConnection {
        limit: Int!
        offset: Int!
        count: Int!
        edges: [Pokemon!]!
    }

    type Pokemon {
        id: ID!
        number: Int!
        name: String!
        ...
    }

index.js

pokemons: (__, args) => {
      const { limit, offset, search, filter } = args.query;
      let pokemons = pokemonsData;

      if (search) {
        const regex = new RegExp(search, 'i');
        pokemons = _.filter(pokemons, p => p.name.match(regex));
      }

      if (filter) {
        if (filter.type) {
          const regex = new RegExp(filter.type, 'i');
          pokemons = _.filter(pokemons,p => _.some(p.types, t => t.match(regex)));
        }

        if (filter.isFavorite) {
          pokemons = _.filter(pokemons, p => !!favorites.get(p.id));
        }
      }

      const count = pokemons.length;
      const edges = pokemons.slice(offset, offset + limit);

      return {
        limit,
        offset,
        count,
        edges
      }
    },

1 个答案:

答案 0 :(得分:0)

我通过有关对象类型https://graphql.org/graphql-js/object-types/的GraphQL文档找到了解决方案。通过将类型嵌套在{}中,可以将类型声明为参数。

{
  pokemons(query: {filter: {type: "Water"}}) {
    edges {
      name
    }
  }
}