带有 JSON 补丁的 GraphQL 变异 [英] GraphQL Mutation with JSON Patch

查看:12
本文介绍了带有 JSON 补丁的 GraphQL 变异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Are there any data types in GraphQL that can be used to describe a JSON Patch operation?

JSON Patch 操作的结构如下.

The structure of a JSON Patch operation is as follows.

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

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

Where value can be any valid JSON literal or object, such as.

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

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

op and path are always simple strings, value can be anything.

推荐答案

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

If you need to return JSON type then graphql have scalar JSON which return any JSON type where you want to return it.

这里是架构

`
 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"

In resolver you can return anything in json format with key name "value"

//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) 
    }
},

唯一需要专门返回值"键来识别以获取查询和变异的东西查询

the only thing you need to specifically return "value" key to identify to get in query and mutation Query

{
  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"
    }
  }
}

这篇关于带有 JSON 补丁的 GraphQL 变异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆