PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, April 18, 2022

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

 April 18, 2022     graphql, laravel, reactjs     No comments   

Issue

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?


Solution

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



Answered By - Albert Tjornejoj
Answer Checked By - Pedro (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing