简体   繁体   English

如何在graphql中查询更新突变?

[英]How I query the update mutation at graphql?

I have my code, and some questions. 我有我的代码,还有一些问题。 1. How can I use the 'updateMessage' Mutation? 1.如何使用“ updateMessage”突变? and 2. Why do I have to use 'Message Class'? 和2.为什么我必须使用“消息类”? or What is different to use that Class? 或使用该类有什么不同?

I know How I can write the query for the createMessage Mutation but I don't know how I write for the updateMessage Mutation. 我知道如何为createMessage Mutation编写查询,但不知道如何为updateMessage Mutation编写查询。

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

var schema = buildSchema(`
type Query{
    getMessage(id: ID!): Message
}
type Mutation {
    createMessage(input: MessageInput): Message
    updateMessage(id: ID!, input: MessageInput): Message
}

input MessageInput {
    content: String
    author: String
}

type Message {
    id: ID!
    content: String
    author: String
}
`);

class Message{
constructor(id,{content, author}){
    this.id = id;
    this.content = content;
    this.author = author;
}
};

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}){
    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);
    }
    fakeDatabase[id] = input;
    return new Message(id,input);
},
};


var app = express();

app.use('/graphql', graphqlHTTP({
schema: schema,
rootValue: root,
graphiql: true,
}));

app.listen (4000, ()=> console.log('Running a GraphQL API server at 
localhost:4000/graphql'));

Question 1: 问题1:

First, you need to create message and get the message id from the response 首先,您需要创建消息并从响应中获取消息ID

mutation {
  createMessage(input: {content:"this is content", author: "john"}) {
    id
    content
    author
  }
}

# response
{
  "data": {
    "createMessage": {
      "id": "956ea83a4ac8e27ff0ec",
      "content": "this is content",
      "author": "john"
    }
  }
}

Then update the message using the message id 然后使用消息ID更新消息

mutation {
  updateMessage(id: "956ea83a4ac8e27ff0ec", input: {content:"this is content", author: "john doe"}) {
    content
    author
  }
}

Finally, check that the message is updated. 最后,检查消息是否已更新。

query {
  getMessage(id: "956ea83a4ac8e27ff0ec") {
    content
    author
  }
}

Question 2: The Message class is act as a model class where it encapsulates related fields into a construct that can be re-used easily. 问题2: Message类充当模型类,在其中将相关字段封装到可以轻松重用的构造中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM