Headless Shopify: Updating custom metafields for a Company object

July 7, 2024
GraphQLRemixHeadless Shopifye-commerce

Unlike Products and Customers in Shopify, the GraphQL mutations CompanyCreate and CompanyUpdate for Companies in the Shopify API do not directly support metafields. Meaning any custom data fields need to be updated using a separate mutation MetafieldsSet.


In the below script, we send a GraphQL mutation to set a metafield for the given company ID. The metafieldValue parameter should be a JavaScript object that will be converted to a JSON string.

  
const shopify = require('./shopifyClient');

async function updateMetafield(companyId, metafieldValue) {
    const query = `
        mutation {
            metafieldsSet(metafields: [
                {
                    ownerId: "${companyId}",
                    namespace: "custom",
                    key: "meta",
                    value: JSON.stringify(metafieldValue) || "{}",
                    type: "json"
                }
            ]) {
                metafields {
                    id
                }
                userErrors {
                    field
                    message
                }
            }
        }
    `;

    try {
        const response = await shopify.query({ data: query });
        console.log(`Metafield updated: ${JSON.stringify(response.body.data)}`);
    } catch (error) {
        console.error(`Error updating metafield: ${error}`);
    }
}

module.exports = updateMetafield;