gpt4 book ai didi

javascript - 我应该在 GraphQL 中使用列表(数组)吗?

转载 作者:搜寻专家 更新时间:2023-10-31 23:11:43 27 4
gpt4 key购买 nike

[以前的标题为“如何从列表中获取 1 条记录...”]

我是 GraphQL 的新手,正在尝试了解如何从查询中获取 1 条记录。

这是我当前查询的结果:

{
"data": {
"todos": null
}
}

我不确定哪里出了问题。我希望结果是这样的:

{
"data": {
"todos": {
"id": 1,
"title": "wake up",
"completed": true
}
}
}

这是我在尝试学习 GraphQL 时创建的代码。

架构.js:

var graphql = require('graphql');

var TODOs = [
{
"id": 1,
"title": "wake up",
"completed": true
},
{
"id": 2,
"title": "Eat Breakfast",
"completed": true
},
{
"id": 3,
"title": "Go to school",
"completed": false
}
];

var TodoType = new graphql.GraphQLObjectType({
name: 'todo',
fields: function () {
return {
id: {
type: graphql.GraphQLID
},
title: {
type: graphql.GraphQLString
},
completed: {
type: graphql.GraphQLBoolean
}
};
}
});

var queryType = new graphql.GraphQLObjectType({
name: 'Query',
fields: function () {
return {
todos: {
type: new graphql.GraphQLList(TodoType),
args: {
id: { type: graphql.GraphQLID }
},
resolve: function (source, args, root, ast) {
if (args.id) {
return TODOs.filter(function(item) {
return item.id === args.id;
})[0];
}

return TODOs;
}
}
}
}
});

module.exports = new graphql.GraphQLSchema({
query: queryType
});

index.js:

var graphql = require ('graphql').graphql;
var express = require('express');
var graphQLHTTP = require('express-graphql');
var Schema = require('./schema');

var query = 'query { todos(id: 1) { id, title, completed } }';
graphql(Schema, query).then( function(result) {
console.log(JSON.stringify(result,null," "));
});

var app = express()
.use('/', graphQLHTTP({ schema: Schema, pretty: true }))
.listen(8080, function (err) {
console.log('GraphQL Server is now running on localhost:8080');
});

要运行此代码,我只需从根目录运行 node index。如何获取记录 ID 返回的一条特定记录?

最佳答案

您的 queryType 的 todos 字段类型错误。它应该是 TodoType,而不是 TodoType 的列表。您收到错误是因为 GraphQL 期望看到一个列表,但您的解析器只返回一个值。

顺便说一下,我建议将 graphiql: true 选项传递给 graphqlHTTP,这样您就可以使用 GraphiQL探索您的架构并进行查询。

关于javascript - 我应该在 GraphQL 中使用列表(数组)吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37981434/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com