【问题标题】:Apollo graphql query with parameters带参数的 Apollo graphql 查询
【发布时间】:2021-04-03 18:02:49
【问题描述】:

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

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

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
  }
}

我得到了成功的响应,但没有数据。如前所述,在 itemsSearch 解析器中记录 term 会打印 undefined。

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

【问题讨论】:

  • 你能试试itemsSearch: (parent, { term }) => {吗?
  • @pzaenger 是的!我现在有term。谢谢你。如果您希望我接受,请添加为答案。
  • 这在同一教程的“下一步”,基础知识中有详细描述
  • 如果要使用变量,别问...graphql.org/learn/queries/#variables

标签: graphql apollo-server


【解决方案1】:

arguments of a resolverparentargscontextinfo

args

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

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

因此,您通过args 获得term

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

或者:

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

【讨论】:

    猜你喜欢
    • 2018-10-19
    • 2019-05-25
    • 2020-10-01
    • 2018-03-02
    • 2021-07-04
    • 2020-02-12
    • 2019-01-28
    • 2019-10-20
    • 2021-02-09
    相关资源
    最近更新 更多