Passing complex arguments to GraphQL mutations

爷,独闯天下 提交于 2021-01-27 05:17:29

问题


I've been using GraphQL in a Node server using graphql-js, and GraphQL has shown to be an extremely valuable abstraction, but I'm running into an issue.

I often find myself needing to pass large structured objects as arguments to GraphQL mutations, using GraphQLInputObjectType. This would be fine, but GraphQL doesn't support the use of JSON notation :(. So I end up just sending a string containing the JSON, for the server to deal with.

const objectStr = JSON.stringify(object).replace(new RegExp("\"", "g"), "'")

graphQLClient(`{
    user: updateUser(someDataObject: "${objectStr}") {...}
}`)

But now I'm not benefiting at all from GraphQL!

I have a feeling I'm doing something wrong here. What is the GraphQL way of sending, say, signup form data, to a mutation?


回答1:


The best way of doing this is to use input objects.

Essentially your request would look like:

/* Query */
mutation Update($input: UpdateUserInput!) {
    updateUser(input: $input) {
        changedUser {
            id
            username
        }
    }
}

/* Variables (as JSON) */
{
    "input": {
        "username": "elon@spacex.com",
        "password": "SuperSecretPassword"
    }
}

You would pass that into the content body of the payload in your POST request as this:

{
    "query": <GraphQL query from above as a string>,
    "variables": <JSON object from above>
}

If you want a deeper explanation, you can check out Scaphold's Docs for updating data to help you structure your API.

Hope this helps!



来源:https://stackoverflow.com/questions/43603182/passing-complex-arguments-to-graphql-mutations

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