graphql - 带参数的 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
}
}
我得到了成功的响应,但没有数据。如前所述,登录term
itemsSearch 解析器打印未定义。
知道如何将该参数传递term
给解析器并获得结果吗?提前致谢。
解决方案
解析器的参数是parent
、args
和:context
info
args
包含为此字段提供的所有 GraphQL 参数的对象。
例如,在执行时
query{ user(id: "4") }
,args
传递给用户解析器的对象是{ "id": "4" }
.
因此,您可以term
通过args
:
itemsSearch: (parent, { term }) => {
...
}
或者:
itemsSearch: (parent, args) => {
const term = args.term;
...
}
推荐阅读
- python - 哪些运算符要重载以使 Python 设置为正常运行
- python - Python 脚本 - 使用 mailmerge 将图像插入 docx 文件
- javascript - 在 HTML 中显示/隐藏 UI 元素的问题
- php - 预处理功能未在主题drupal 8上运行
- image - iText7 将 SVG 添加到 PdfDocument 并在 PDF 中正确对齐 SVG 图像
- python - 按名称使用自动连接插槽
- php - 防止 Laravel 中同时发生模型突变的最佳方法
- .net - 实体框架返回一个字段
- wordpress - 在 Wordpress REST API 中按菜单顺序排序?
- docusignapi - 收件人视图未合并