gpt4 book ai didi

带有 JSON 补丁的 GraphQL 突变

转载 作者:行者123 更新时间:2023-12-04 15:46:18 25 4
gpt4 key购买 nike

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 可以是任何东西。

最佳答案

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

关于带有 JSON 补丁的 GraphQL 突变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55624691/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com