首页 > 解决方案 > 带参数的 Apollo graphql 查询

问题描述

我正在关注这个 Graphql 介绍https://www.apollographql.com/docs/apollo-server/getting-started/。我已经设置好我的文件(稍作修改),并且基本查询正在 http://localhost:4000/ 上运行。

学完基础后我的下一个问题是,如何根据参数获取数据?我已经做到了这一点,但是操场上的查询没有返回结果。

index.js

const typeDefs = gql`
    type Item {
        name: String
        description: String
        full_url: String
        term: String
    }

    type Query {
        items: [Item]
        itemsSearch(term: String!): [Item]
    }
`;

const resolvers = {
    Query: {
        // this works. it is the example from the guide.
        items: () => items,
        // this doesn't work. `term` is always undefined
        itemsSearch: term => {
            console.log('term', term);
            console.log('items', items);
            return items.filter(item => item.title.indexOf(term) > -1 || item.author.indexOf(term) > -1);
        },
    },
};

然后我在操场上运行这个查询。(主要来自https://graphql.org/graphql-js/passing-arguments/

{
  itemsSearch(term: "Rowling") {
    title
    author
  }
}

我得到了成功的响应,但没有数据。如前所述,登录termitemsSearch 解析器打印未定义。

知道如何将该参数传递term给解析器并获得结果吗?提前致谢。

标签: graphqlapollo-server

解决方案


解析器的参数是parentargs和:contextinfo

args

包含为此字段提供的所有 GraphQL 参数的对象。

例如,在执行时query{ user(id: "4") }args 传递给用户解析器的对象是{ "id": "4" }.

因此,您可以term通过args

itemsSearch: (parent, { term }) => {
   ...
}

或者:

itemsSearch: (parent, args) => {
   const term = args.term;
   ...
}

推荐阅读