javascript - 当我通过 graphiql 发送查询时,graphql JS 返回 null
问题描述
我想我已经彻底检查了这段代码,但找不到错误请帮忙!!查询 id 时返回空值
另外,vscode 告诉我我的父母在 resolve 函数中没有使用。我在这里做错了什么?
表示 - -
const express = require('express');
const graphqlHTTP = require('express-graphql');
const schema = require('./schema/schema')
const app = express();
app.use('/graphql', graphqlHTTP({
schema,
graphiql:true
}));
app.listen(1991, ()=> {
console.log('1991 live');
});
架构——
const graphql = require('graphql');
const _= require('lodash');
const { GraphQLObjectType, GraphQLString, GraphQLID, GraphQLInt,
GraphQLSchema } = graphql;
var drugs = [
{name: 'Paracetamol', price: 200, qty: 20, drugid: 1},
{name: 'Amoxicilin', price: 700, qty: 10, drugid: 2}
];
var categories = [
{name: 'Painkiller', id: 1},
{name: 'Anti-Biotic', id: 2}
];
const DrugType = new GraphQLObjectType({
name: 'Drug',
fields: () => ({
name: {type: GraphQLString},
price: {type: GraphQLInt},
qty: {type: GraphQLInt},
drugid: {type: GraphQLID}
})
});
const DrugCategory = new GraphQLObjectType({
name: 'Category',
fields: () => ({
name: {type: GraphQLString},
id: {type: GraphQLID}
})
});
const RootQuery = new GraphQLObjectType({
name: 'RootQueryType',
fields: {
drug:{
type: DrugType,
args:{id:{type: GraphQLID}},
resolve(parent, args){
return _.find(drugs, {drugid:args.id});
}
},
category:{
type: DrugCategory,
args:{id: {type: GraphQLID}},
resolve(parent,args){
return _.find(categories, {id:args.id});
}
}
}
});
module.exports = new GraphQLSchema({
query: RootQuery
});
这是我在 graphiql 中查询时得到的结果
询问 -
{
drug(id: 1){
name
}
}
结果 -
{
"data": {
"drug": null
}
}
解决方案
您传递给 lodashfind
方法的对象是{ id: args.id }
- 这意味着您正在寻找一个具有id
匹配属性的对象args.id
。但是,drugs
数组中的所有对象都没有id
属性。更新您的数组或更改您的搜索条件(即{ drugid: args.id }
)。
此外,您的id
参数类型是GraphQLID
,它被视为字符串。这意味着find
将 String 参数与 Number 属性值进行比较。将参数的类型更改为GraphQLInt
,或使用换args.id
行Number.parseInt
,或将drugId
值更改为字符串。
推荐阅读
- javascript - Zip文件作为javascript中的缓冲区
- python - DocxTemplate 复制整个文档并将其粘贴到另一个(= ctrl A + ctrl V)
- python - Python - 使用 get_forget() 时标签不会隐藏
- html - 黑盒区域地图标签
- c# - Word Content Control 里面的重复单词
- ios - Flutter 自动完成谷歌地方表格
- c# - 包含在 GetAll 方法中(ASP.NET 样板)
- amazon-web-services - 我可以恢复被覆盖的 AWS Lambda 函数或获取一些以前部署的函数更改吗
- python - 尝试连接到使用 Django 准备的 API 时收到错误请求警告
- json - 如何使用 jsonter、plokhotnyuk 的地图将 json 解析为案例类