GraphQL Mutation with JSON Patch

╄→гoц情女王★ 提交于 2020-08-05 07:18:21

问题


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

The structure of a JSON Patch operation is as follows.

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

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

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

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


回答1:


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

Here is schema

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

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

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


来源:https://stackoverflow.com/questions/55624691/graphql-mutation-with-json-patch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!