Home > Software engineering >  Cannot return null for non-nullable field in a GraphQL query
Cannot return null for non-nullable field in a GraphQL query

Time:07-31

const { ApolloServer, gql } = require('apollo-server-express');
const express = require('express');
// dummy data
const books = [
  { id: 1, title: 'book1', author: 'author1' },
  { id: 2, title: 'book2', author: 'author2' },
  { id: 3, title: 'book3', author: 'author3' },
];
const typeDefs = gql`
  type Book {
    id: ID!
    title: String!
    author: String!
  }
  type Query {
    hello: String
    books: [Book!]!
    book(id: ID!): Book
  }
`;
const resolvers = {
  Query: {
    hello: () => 'Hello World',
    books: () => books,
    book: (parent,args) => {
      return books.find((book) => book.id === args.id);
    },
  },
};
async function apolloServer(typeDefs, resolvers) {
  try {
    const server = new ApolloServer({ typeDefs, resolvers });
    const app = express();
    await server.start();
    server.applyMiddleware({ app, path: '/api' });
    app.listen(6999, () => console.log('Server is running on 6999'));
  } catch (e) {
    console.log(e);
  }
}
apolloServer(typeDefs, resolvers);

The result I am getting in GraphQL play Ground while runnig the following Query at localhost 6999 is :- "message": "Cannot return null for non-nullable field Query.book.", I am writing the following query :-

query($bookId: ID!){
  book(id: $bookId) {
    id
  }
}

passing variable as

{
  "bookId": "2"
}

CodePudding user response:

In the code as it seems I was trying to "===" between 'ID' and 'Int' type, Upon changing the book args as book(id: Int) I got my query resolved

const typeDefs = gql`
  type Book {
    id: ID!
    title: String!
    author: String!
  }
  type Query {
    hello: String
    books: [Book!]!
    book(id: ID!): Book
  }
`;

I am getting following response

{
  "data": {
    "book": {
      "id": "1",
      "title": "book1"
    }
  }
}
  • Related