" value as JSON with the help of JSON Scalar. But how to pass JSON value whi" /> " value as JSON with the help of JSON Scalar. But how to pass JSON value whi" /> " value as JSON with the help of JSON Scalar. But how to pass JSON value whi"/>

How to pass JSON value from GraphQL to back-end?

1.2k views Asked by At

Using the Extended graphQL scalars we can display the "Map<String, String>" value as JSON with the help of JSON Scalar. But how to pass JSON value while storing the Data?

The schema :

Type Mutation{
               createProduct(ProductRequest: ProductInput) : Product
             }

input ProductInput{
    id : Int
    name: String
    attributes: JSON
}

The Query :

mutation {
  createProduct(ProductRequest: {
        id:1,
        name:"ABC"
  attributes:{
    Key: "Value"
  }
  })
  {
    id
    name
    attributes
  }
}

If I pass like this, for "Attributes" it's taking as null. So nothing is getting stored in database. If anybody knows to pass JSON value in graphQL, please let me know.

I tried passing the data using "PostMapping" and it worked! But I need to pass from GraphQL.

1

There are 1 answers

2
Skerdi Velo On

to pass a JSON value while storing data in GraphQL I tried to use the JSON scalar type that you have already defined in your schema. To pass a JSON value, you can simply provide a valid JSON string as the value for the attributes field in your mutation. I tried your code and this works for me:

import { gql } from '@apollo/client';

const CREATE_PRODUCT_MUTATION = gql`
  mutation CreateProduct($productRequest: ProductInput!) {
    createProduct(ProductRequest: $productRequest) {
      id
      name
      attributes
    }
  }
`;

const productRequest = {
  id: 1,
  name: "ABC",
  attributes: {
    Key1: "Value1",
    Key2: "Value2",
    Key3: "Value3"
  }
};

client.mutate({
  mutation: CREATE_PRODUCT_MUTATION,
  variables: {
    productRequest: productRequest
  }
}).then(result => {
  console.log(result.data.createProduct);
}).catch(error => {
  console.error(error);
});

In this piece of code , I'm passing a JSON string as the value for the attributes field. Which should fix your problem.