Mdd Mdd - 5 months ago 24
Node.js Question

How to get 1 record from a list in GraphQL

I am very new to GraphQL and trying to understand how to get 1 record from query.

This is the result of my current query:

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


I am not sure what is wrong. I would like the result to be this:

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


Here is my code that I've created as I try to learn 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');
});


To run this code I just run
node index
from the root directory. How can I get one specific record returned by the records id?

Answer

You have the wrong type for the todos field of your queryType. It should be TodoType, not a list of TodoType. You're getting an error because GraphQL expects to see a list, but your resolver is just returning a single value.

By the way, I suggest passing the graphiql: true option to graphqlHTTP, which will let you use GraphiQL to explore your schema and make queries.