[之前标题为"如何从列表中获取1条记录..."]
我是GraphQL的新手,并试图了解如何从查询中获取1条记录。
这是我当前查询的结果:
{
"data": {
"todos": null
}
}
我不确定是什么问题。我希望结果如下:
{
"data": {
"todos": {
"id": 1,
"title": "wake up",
"completed": true
}
}
}
这是我在尝试学习GraphQL时创建的代码。
schema.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返回的特定记录?
答案 0 :(得分:4)
queryType的todos字段的类型错误。它应该是TodoType
,而不是TodoType
的列表。您收到错误是因为GraphQL希望看到一个列表,但您的解析器只返回一个值。
顺便提一下,我建议将graphiql: true
选项传递给graphqlHTTP,这样您就可以使用GraphiQL来探索架构并进行查询。