Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert the object array to GraphQL format in Javascript?

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

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

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

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?

like image 601
Albert Tjornejoj Avatar asked Jan 03 '23 20:01

Albert Tjornejoj


1 Answers

Finally this was my solution:

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

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

like image 135
Albert Tjornejoj Avatar answered Jan 05 '23 15:01

Albert Tjornejoj