如何从GraphQL的列表中获取1条logging

我对GraphQL很陌生,并试图理解如何从查询中获得1条logging。

这是我目前的查询的结果:

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

我不知道什么是错的。 我想结果是这样的:

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

这是我在学习GraphQL时创build的代码。

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 。 我怎样才能得到一个loggingID返回的特定logging?

您的queryType的todos字段的types是错误的。 它应该是TodoType ,而不是TodoType的列表。 你得到一个错误,因为GraphQL希望看到一个列表,但你的parsing器只是返回一个值。

顺便说一下,我build议将graphiql: true选项传递给graphqlHTTP,这将允许您使用GraphiQL来浏览您的模式并进行查询。