带参数的 Apollo graphql 查询
Apollo graphql query with parameters
我正在关注这个 Graphql 介绍 https://www.apollographql.com/docs/apollo-server/getting-started/。我已经设置了我的文件(稍作修改),并且基本查询正在 http://localhost:4000/ 上运行。
学完基础知识后我的下一个问题是,如何根据参数获取数据?我已经走到这一步了,但是 playground 中的查询没有 return 结果。
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);
},
},
};
然后我 运行 在 playground 中进行此查询。 (主要工作于 https://graphql.org/graphql-js/passing-arguments/)
{
itemsSearch(term: "Rowling") {
title
author
}
}
我得到了成功的响应,但没有数据。如前所述,在 itemsSearch 解析器中记录 term
会打印 undefined.
知道如何将参数 term
传递给解析器并获得结果吗?提前致谢。
arguments of a resolver 是 parent
、args
、context
和 info
:
args
An object that contains all GraphQL arguments provided for this field.
For example, when executing query{ user(id: "4") }
, the args
object passed to the user resolver is { "id": "4" }
.
因此,您通过 args
获得 term
,其中:
itemsSearch: (parent, { term }) => {
...
}
或:
itemsSearch: (parent, args) => {
const term = args.term;
...
}
我正在关注这个 Graphql 介绍 https://www.apollographql.com/docs/apollo-server/getting-started/。我已经设置了我的文件(稍作修改),并且基本查询正在 http://localhost:4000/ 上运行。
学完基础知识后我的下一个问题是,如何根据参数获取数据?我已经走到这一步了,但是 playground 中的查询没有 return 结果。
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);
},
},
};
然后我 运行 在 playground 中进行此查询。 (主要工作于 https://graphql.org/graphql-js/passing-arguments/)
{
itemsSearch(term: "Rowling") {
title
author
}
}
我得到了成功的响应,但没有数据。如前所述,在 itemsSearch 解析器中记录 term
会打印 undefined.
知道如何将参数 term
传递给解析器并获得结果吗?提前致谢。
arguments of a resolver 是 parent
、args
、context
和 info
:
args
An object that contains all GraphQL arguments provided for this field.
For example, when executing
query{ user(id: "4") }
, theargs
object passed to the user resolver is{ "id": "4" }
.
因此,您通过 args
获得 term
,其中:
itemsSearch: (parent, { term }) => {
...
}
或:
itemsSearch: (parent, args) => {
const term = args.term;
...
}