How to convert JSON format of data to GraphQL query format

How to convert JSON format of data to GraphQL query format


6

I have a Json object and want to convert it to graphql query in order to post a request on graphql api. Can any one please provide any pointer to it as I am not able to proceed.

JSON object extracted from the POJO:
{
  "customer": {
     "idFromSource": "123", 
     "title": "Mrs", 
     "dateOfBirth": "1980-11-11"
  }
}

graphql query that I need to hit a post request:
{
  "query": "mutation {updateCustomer(customer: 
                    {idFromSource: "123", 
                    title: "Mrs", 
                    dateOfBirth: "1980-11-11"})
                     {idFromSource title dateOfBirth}}"
}

2

2 Answers
2


5

Declare the input as a variable in your query. Queries should be static. That means you never generate GraphQL code on the client. If you are doing that you are probably doing something wrong. I am not sure which frontend technology you are using but here is your query using JavaScript fetch:

let json = // ... parsed JSON

let query = `
  mutation customerMutation($customer: CustomerInput) { # Adjust typename
    updateCustomer(customer: $customer) {
      idFromSource
      title
      dateOfBirth
    }
  }
`;

fetch('/graphql', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  data: JSON.stringify({
    query,
    variables: { customer: json.customer }
  }),
});

The trick is that there is a type on the GraphQL API (I have here assumed it is called CustomerInput, please adjust it in the mutation) that has the same shape as your JSON object. The server will therefore happily accept the whole JSON object as a value for the $customer variable in the mutation. No conversion needed!


-1

I use this module json-to-graphql-query

New contributor

Vetalgo is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

1

  • Vetalgo, please don't just post some tool or library as an answer. At least demonstrate how it solves the problem in the answer itself.

    – jmoerdyk

    29 mins ago



Leave a Reply

Your email address will not be published. Required fields are marked *