【问题标题】:How I query the update mutation at graphql?如何在 graphql 上查询更新突变?
【发布时间】:2019-05-24 11:07:20
【问题描述】:

我有我的代码,还有一些问题。 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'));

【问题讨论】:

    标签: graphql express-graphql


    【解决方案1】:

    问题 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 类充当模型类,它将相关字段封装到一个可以轻松重用的构造中。

    【讨论】:

      猜你喜欢
      • 2021-06-04
      • 2017-08-24
      • 2018-07-04
      • 2021-12-02
      • 2018-09-17
      • 2022-06-23
      • 2022-11-25
      • 2017-10-17
      • 2020-05-30
      相关资源
      最近更新 更多