RRR uzumaki
RRR uzumaki

Reputation: 1328

Error while returning data from Graphql endpoint

I started with the very basic example of Graphql.So the error i am facing is

{
  "errors": [
    {
      "message": "Cannot return null for non-nullable field Event.title.",
      "locations": [
        {
          "line": 34,
          "column": 5
        }
      ],
      "path": [
        "createevent",
        "title"
      ]
    }
  ],
  "data": {
    "createevent": null
  }
}

and the code for my graphql endpoint is

const express = require("express");
const bodyparser = require("body-parser");
const graphqlhttp = require("express-graphql");
const { buildSchema } = require("graphql");
const app = express();
app.use(bodyparser.json());
const events = [];
app.use(
  "/graphql",
  graphqlhttp({
    schema: buildSchema(`
    type Event {
      _id:ID!
      title:String!
      description:String!
      price:Float!
      date:String!
    }
    input Eventinput{
      title:String!
      description:String!
      price:Float!
      date:String!
    }
    type rootquery {
        events:[Event!]!

    }
    type rootmutation {
        createevent(eventinput:Eventinput):Event
    }
    schema{
        query:rootquery
        mutation:rootmutation
    }
    `),
    rootValue: {
      events: () => {
        return events;
      },
      createevent: args => {
        const event = {
          _id: Math.random().toString(),
          title: args.eventinput.title,
          description: args.eventinput.description,
          price: +args.eventinput.price,
          date: args.eventinput.date
        };
        events.push(event);
        console.log(events)
        return events
      }
    },
    graphiql: true
  })
);
app.listen(3000);

Now when i console.log(events).It actually gives me all the values that i need correctly,but on localhost:3000/graphql while running the command

mutation {
  createevent(eventinput:{title:"Test",description:"dont",price:23.4,date:"2019-08-25T06:47:10.585Z"}){
    title
    description
  }
}

I am receiving the error that i stated above even though i have checked this twice i am unable to find the issue but then my code works when i try to fetch the Event by

query{
  events{
    title
    price
  }
}

only after creating event i see error above but that thing actually works behind the scene!!

Upvotes: 2

Views: 741

Answers (1)

user10706046
user10706046

Reputation:

events.push(event)
console.log(events)
return events

You are returning the array, but in your GraphQL typedefs you have

type rootmutation {
        createevent(eventinput:Eventinput):Event
    }

which indicates you intend to send a single "Event" object. For an array, it should be createevent(eventinput:Eventinput):[Event]. Not sure if it will fix your error entirely but it's part of the problem.

Upvotes: 2

Related Questions