【问题标题】:GraphQL Mutation with JSON Patch带有 JSON 补丁的 GraphQL 突变
【发布时间】:2021-08-18 04:22:41
【问题描述】:

GraphQL 中是否有任何数据类型可用于描述 JSON Patch 操作?

JSON Patch 操作的结构如下。

{ "op": "add|replace|remove", "path": "/hello", "value": ["world"] }

其中value 可以是任何有效的 JSON 文字或对象,例如。

"value": { "name": "michael" }
"value": "hello, world"
"value": 42
"value": ["a", "b", "c"]

oppath 总是简单的字符串,value 可以是任何东西。

【问题讨论】:

    标签: graphql json-patch


    【解决方案1】:

    如果你需要返回 JSON 类型,那么 graphql 有 scalar JSON 它返回您想要返回的任何 JSON 类型。

    这是架构

    `
     scalar JSON
     type Response {
       status: Boolean
       message: String
       data: JSON
     }
     type Test {
       value: JSON
     }
     type Query {
       getTest: Test
     }
     type Mutation {
       //If you want to mutation then pass data as `JSON.stringify` or json formate
       updateTest(value: JSON): Response
     }
    `
    

    在解析器中,您可以返回任何带有键名 "value" 的 json 格式的内容

    //Query resolver
    getTest: async (_, {}, { context }) => {
        // return { "value": "hello, world" }
        // return { "value": 42 }
        // return { "value": ["a", "b", "c"] }
        // return anything in json or string
        return { "value": { "name": "michael" } }
    },
    // Mutation resolver
    async updateTest(_, { value }, { }) {
        // Pass data in JSON.stringify
        // value : "\"hello, world\""
        // value : "132456"
        // value : "[\"a\", \"b\", \"c\"]"
        // value : "{ \"name\": \"michael\" }"
        console.log( JSON.parse(value) )
        //JSON.parse return formated required data
        return { status: true,
                 message: 'Test updated successfully!',
                 data: JSON.parse(value) 
        }
    },
    

    您唯一需要专门返回“值”键来识别以进行查询和变异 查询

    {
      getTest {
        value
      }
    }
    // Which return 
    {
      "data": {
        "getTest": {
          "value": {
            "name": "michael"
          }
        }
      }
    }
    

    变异

    mutation {
      updateTest(value: "{ \"name\": \"michael\" }") {
        data
        status
        message
      }
    }
    // Which return 
    {
      "data": {
        "updateTest": {
          "data": null,
          "status": true,
          "message": "success"
        }
      }
    }
    

    【讨论】:

    • 我正在使用 graphql-dotnet,所以需要找到一种方法来应用它。谢谢!
    猜你喜欢
    • 2017-07-28
    • 2023-03-05
    • 1970-01-01
    • 1970-01-01
    • 2021-08-27
    • 2015-07-17
    • 2021-03-13
    • 2021-02-24
    相关资源
    最近更新 更多