【发布时间】: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