将复杂的参数传递给GraphQL突变 [英] Passing complex arguments to GraphQL mutations

查看:70
本文介绍了将复杂的参数传递给GraphQL突变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用graphql-js在Node服务器中使用GraphQL,而GraphQL已被证明是一种非常有价值的抽象,但是我遇到了一个问题.

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.

我经常发现自己需要使用 GraphQLInputObjectType 将大型结构化对象作为GraphQL突变的参数传递.这样做很好,但是GraphQL不支持使用JSON表示法:(.因此,我最终只发送了一个包含JSON的字符串,供服务器处理.

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}") {...}
}`)

但是现在我根本无法从GraphQL中受益!

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?

推荐答案

最好的方法是使用输入对象.

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

您可以这样将其传递到POST请求中有效负载的内容主体中:

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

如果您想要更深入的说明,可以查看 Scaphold的文档以更新数据帮助您构建API.

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

希望这会有所帮助!

这篇关于将复杂的参数传递给GraphQL突变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆