簡體   English   中英

如何在graphql中查詢更新突變?

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

我有我的代碼,還有一些問題。 1.如何使用“ updateMessage”突變? 和2.為什么我必須使用“消息類”? 或使用該類有什么不同?

我知道如何為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'));

問題1:

首先,您需要創建消息並從響應中獲取消息ID

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

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

然后使用消息ID更新消息

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

最后,檢查消息是否已更新。

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

問題2: Message類充當模型類,在其中將相關字段封裝到可以輕松重用的構造中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM