简体   繁体   English

将复杂参数传递给GraphQL突变

[英]Passing complex arguments to GraphQL mutations

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. 我一直在使用graphql-js在Node服务器中使用GraphQL,并且GraphQL已经证明是一个非常有价值的抽象,但我遇到了一个问题。

I often find myself needing to pass large structured objects as arguments to GraphQL mutations, using GraphQLInputObjectType . 我经常发现自己需要使用GraphQLInputObjectType将大型结构化对象作为GraphQL突变的参数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. 这没关系,但GraphQL不支持使用JSON表示法:(。所以我最终只发送一个包含JSON的字符串,供服务器处理。

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

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

But now I'm not benefiting at all from GraphQL! 但是现在我从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? 什么是GraphQL方式,例如,将注册表单数据发送到变异?

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: 您可以将其传递到POST请求中的有效负载的内容主体中,如下所示:

{
    "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. 如果您需要更深入的解释,可以查看Scaphold的文档以更新数据,以帮助您构建API。

Hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM