如何在Javascript中将对象数组转换为GraphQL格式? [英] How can I convert the object array to GraphQL format in Javascript?

查看:43
本文介绍了如何在Javascript中将对象数组转换为GraphQL格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用React,并发送以下信息:

I'm working with React, and I send this information:

const imageServicesClean = JSON.stringify(imageServices);
const query = `
    mutation {
        companyUpdate(
                idCompany:${idCompany},
                name:${nameClean},
                imageServices:${imageServicesClean})
            {
            idCompany
            name
            imageServices {
                idImageService
                name
                url
                key
            }
        }
    }`;

并且以这种方式发送imageServicesClean,但是返回错误:

And the imageServicesClean is sent in this way, but return error:

[{
    "idImageService": 1,
    "name": "Service1",
    "url": "",
    "key": "asdasdas"
}, {
    "idImageService": 2,
    "name": "Service2",
    "url": "sdsads",
    "key": "sddsfsds_"
}]

因为我的GraphQL服务器(Laravel)只允许变量不带引号,所以这种方式:

Because my GraphQL server (Laravel) just allows the variable without quotes, in this way:

[{
    idImageService: 1,
    name: "Service1",
    url: "",
    key: "sdofunc4938urcnnwikk"
}, {
    idImageService: 2,
    name: "Service2",
    url: "sdsads",
    key: "sddsfsdssss8347yuirh"
}]

因此,函数 JSON.stringify 在GraphQL中不适用于构建格式.如何在Javascript中将对象数组转换为GraphQL格式?

So the function JSON.stringify don't work for build format in GraphQL. How can I convert the object array to GraphQL format in Javascript?

推荐答案

最后,这是我的解决方案:

Finally this was my solution:

const imageServicesClean = JSON.stringify(imageServices);
const graphQLImageServices = imageServicesClean.replace(/"([^(")"]+)":/g,"$1:");

但是最终我正在使用该库,它为我做了所有工作: https://github.com/atulmy/gql-query-builder

But finally I'm working with this library, it does everything for me: https://github.com/atulmy/gql-query-builder

这篇关于如何在Javascript中将对象数组转换为GraphQL格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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