简体   繁体   中英

How I query the update mutation at graphql?

I have my code, and some questions. 1. How can I use the 'updateMessage' Mutation? and 2. Why do I have to use 'Message Class'? 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.

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:

First, you need to create message and get the message id from the response

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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