javascript - 从 Graphql 端点返回数据时出错

标签 javascript node.js graphql

我从 Graphql 的非常基本的示例开始。所以我面临的错误是

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

我的 graphql 端点的代码是

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);

现在,当我 console.log(events) 时。它实际上为我提供了我正确需要的所有值,但是在运行命令时在 localhost:3000/graphql 上

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

我收到了上面所说的错误,尽管我已经检查了两次,但我无法找到问题,但是当我尝试通过以下方式获取事件时,我的代码可以工作

query{
  events{
    title
    price
  }
}

只有在创建事件后我才会看到上面的错误,但那件事实际上在幕后工作!!

最佳答案

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

您正在返回数组,但在 GraphQL typedef 中您有

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

这表明您打算发送单个“Event”对象。对于数组,它应该是createevent(eventinput:Eventinput):[Event]。不确定它是否能完全解决您的错误,但它是问题的一部分。

关于javascript - 从 Graphql 端点返回数据时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57643912/

相关文章:

javascript - 在 javascript 中的元素中添加/删除类名之间切换

javascript - 在 JS 中创建空 div 时出现未捕获类型错误

javascript - rxjs 限制获取直到请求完成

javascript - 流式传输不同语言的 mp4 视频 (ExpressJs)

asp.net - GraphQL.NET : How to separate the root query into multiple parts

reactjs - 从 React 客户端调用 graphQL 查询

javascript - npm start 是如何工作的,应该是 npm run start 吧? (创建 react 应用程序)

node.js - docker : Linking containers on different host machines

javascript - 如何通过 Mongoose 中的对象数组查找?

node.js - 在 GraphQL 中处理 Mongoose 填充字段