如何在GraphQL

时间:2018-06-15 17:15:28

标签: node.js express graphql

实际上,我是graphQL的新手,因此我无法在graphiQL中的函数updateMessage()中正确传递参数。我尝试使用

更新数据库
mutation {
  createMessage(input: {
    author: "Pawan",
    content: "hope is a dangerous thing",
  }) {
    id,content,author,
  }
 updateMessage(id:{cfe934d60b9997a4507e},input:{
    author: "Pawan",
    content: "hope is a dangerous thing",
  })
}

但错误显示为

{
  "errors": [
    {
      "message": "Syntax Error: Expected :, found }",
      "locations": [
        {
          "line": 8,
          "column": 40
        }
      ]
    }
  ]
}

除此之外我也无法展示fakeDatabase。我能这样做吗? 如果是,我每次向fakeDatabase添加消息时如何显示?

mutation.js

      var express = require('express');
        var graphqlHTTP = require('express-graphql');
        var { buildSchema } = require('graphql');

    // Construct a schema, using GraphQL schema language
    var schema = buildSchema(`
      input MessageInput {
        content: String
        author: String
      }

      type Message {
        id: ID!
        content: String
        author: String
      }

      type Query {
        getMessage(id: ID!): Message
      }

      type Mutation {
        createMessage(input: MessageInput): Message
        updateMessage(id: ID!, input: MessageInput): Message
      }
    `);

    // If Message had any complex fields, we'd put them on this object.
    class Message {
      constructor(id, {content, author}) {
        this.id = id;
        this.content = content;
        this.author = author;
      }
    }

    // Maps username to content
    var fakeDatabase = {};

    var root = {
      getMessage: function ({id}) {
        if (!fakeDatabase[id]) {
          throw new Error('no message exists with id ' + id);
        }
        return new Message(id, fakeDatabase[id]);
      },
      createMessage: function ({input}) {
        // Create a random id for our "database".
        var id = require('crypto').randomBytes(10).toString('hex');

        fakeDatabase[id] = input;
        return new Message(id, input);
      },
      updateMessage: function ({id, input}) {
        if (!fakeDatabase[id]) {
          throw new Error('no message exists with id ' + id);
        }
        // This replaces all old data, but some apps might want partial update.
        fakeDatabase[id] = input;
        return new Message(id, input);
      },
    };

    var app = express();
    app.use('/graphql', graphqlHTTP({
      schema: schema,
      rootValue: root,
      graphiql: true,
    }));
    console.log(fakeDatabase)
    app.listen(4000, () => {
      console.log('Running a GraphQL API server at localhost:4000/graphql');

    });

1 个答案:

答案 0 :(得分:0)

在您的变异updateMessage上尝试更新参数并将$id作为字符串而不是对象发送,例如:

updateMessage(id:"cfe934d60b9997a4507e",input:{
    author: "Pawan",
    content: "hope is a dangerous thing",
  })

问题是变异updateMessage需要IDMessageInput,但您发送ObjectMessageInput