Querying a Metaobject Via Its GID in GraphQL

Querying a Metaobject Via Its GID in GraphQL

Snarkov
Visitor
2 0 0

Im trying to query a metaobject via its GID, which I get from querying the metafield Ive attached it to, but am having no luck.

 

In my setup im using Gatsby for the front end and gatsby-source-shopify. Im using Netlify to run the fetching of the Metafields and Metaobjects data.

 

This is my GraphQL query, Im not sure if I've structured it correctly, as Im getting Non Valid JSON as a response. 

Note everything is single line text except custom values which is JSON.

 

 

import fetch from 'node-fetch';

export const handler = async (event, context) => {
  const metaobjectGID = event.queryStringParameters.gid;
  const GATSBY_SHOPIFY_ACCESS_TOKEN = process.env.GATSBY_SHOPIFY_ACCESS_TOKEN;
  const GATSBY_SHOPIFY_SHOP_NAME = process.env.GATSBY_SHOPIFY_SHOP_NAME;

  // GraphQL query to fetch details from the metaobject
  const query = `
  query {
    node(id: "${metaobjectGID}") {
      ... on nutrition_panel_url {
        energy_per_serve
        protein_per_serve
        gluten_per_serve
        total_fat_per_serve
        saturated_fat_per_serve
        total_carbs_per_serving
        sugar_per_serving
        total_sodium_per_serving
        custom_values
      }
    }
  }
`;


  try {
    // Make the GraphQL request to Shopify
    const response = await fetch(`https://${GATSBY_SHOPIFY_SHOP_NAME}/admin/api/2024-01/graphql.json`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-Shopify-Access-Token': GATSBY_SHOPIFY_ACCESS_TOKEN,
      },
      body: JSON.stringify({ query }),
    });

    const text = await response.text();
    console.log('Raw Shopify response:', text);

    // Check if the response is okay
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }

    // Parse the response as JSON
    const data = await response.json();

    // Return the JSON data
    return {
      headers: {
        "Access-Control-Allow-Origin": "*", // Allows requests from any origin
      },
      body: JSON.stringify(data),
    };
  } catch (error) {
    // Log any errors that occur during the fetch operation
    console.error("Error in fetch operation:", error);

    // Return an error response
    return {
      statusCode: 500,
      body: JSON.stringify({ error: "Internal Server Error" }),
    };
  }
};

I believe I'm fetching this correctly for the frontend but happy to provide further code if needed!

Replies 0 (0)