带有 JSON 补丁的 GraphQL 突变

2024-01-09

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

JSON Patch 操作的结构如下。

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

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

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

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


如果你需要返回 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
 }
`

在解析器中,您可以返回带有键名的 json 格式的任何内容"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) 
    }
},

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

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

Mutation

mutation {
  updateTest(value: "{ \"name\": \"michael\" }") {
    data
    status
    message
  }
}
// Which return 
{
  "data": {
    "updateTest": {
      "data": null,
      "status": true,
      "message": "success"
    }
  }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

带有 JSON 补丁的 GraphQL 突变 的相关文章

随机推荐