Formatting JSON response from graphql-js-client query

azmansalleh
New Member
1 0 0

Hi all,

I need some advice on properly utilising the graphql-js-client library provided by Shopify. I currently am trying to retrieve some product information from my Storefront API which works but need help in formatting the JSON response returned by the endpoint.

Below is an excerpt of my query that retrieves the product information

 

export const products = client.query((root) => {
    root.add('shop', (shop) => {
        shop.addConnection('products', {args: {first: 10}}, (product) => {
            product.add('title', {alias:'name'});
            product.add('description');
            product.add('totalInventory', {alias:'currentInventory'});
            product.add('priceRange', {alias:'price'} , (productPriceRange) => {
                productPriceRange.addInlineFragmentOn('minVariantPrice', (moneyV2) => {
                    moneyV2.add('amount');
                })
            });
        });
    });
});

 

 

When running sending this query it will return the following response:

 

{
  id: 'Z2lkOi8vc2hvcGlmeS9Qcm9kdWN0LzYyMjk3MTE2MTgyNDY=',
  name: 'Timber Gray Sofa 2.0',
  description: 'Stay a while. The Timber charme chocolat sofa is set atop an oak trim and flaunts fluffy leather back and seat cushions. Over time, this brown leather sofa’s full-aniline upholstery will develop a worn-in vintage look. Snuggle up with your cutie (animal or human) and dive into a bowl of popcorn. This sofa is really hard to leave. Natural color variations, wrinkles and creases are part of the unique characteristics of this leather. It will develop a relaxed vintage look with regular use.',
  currentInventory: 4,
  price: { minVariantPrice: { amount: '1000.0' } }
}

 

As we can see the price amount field is nested twice in an object. Using the same library and methods, it is possible to return the response in this manner instead:

 

{
  id: 'Z2lkOi8vc2hvcGlmeS9Qcm9kdWN0LzYyMjk3MTE2MTgyNDY=',
  name: 'Timber Gray Sofa 2.0',
  description: 'Stay a while. The Timber charme chocolat sofa is set atop an oak trim and flaunts fluffy leather back and seat cushions. Over time, this brown leather sofa’s full-aniline upholstery will develop a worn-in vintage look. Snuggle up with your cutie (animal or human) and dive into a bowl of popcorn. This sofa is really hard to leave. Natural color variations, wrinkles and creases are part of the unique characteristics of this leather. It will develop a relaxed vintage look with regular use.',
  currentInventory: 4,
  price: '1000.0' 
}

 

 

I appreciate if someone can point me to the right direction. Thank you!

0 Likes