Edits history of script submission #23723 for ' Get Metafields (shopify)'

  • bunnative
    One script reply has been approved by the moderators
    Ap­pro­ved
    //native
    
    /**
     * Get Metafields
     * List the metafields of any resource that has them (product, variant, customer, order, collection, shop, ...), given its GID (e.g. `gid://shopify/Product/123`), optionally limited to one namespace. Returns one page; pass pageInfo.endCursor as after for the next.
     */
    export async function main(
      auth: RT.Shopify,
      owner_id: string,
      namespace: string | undefined,
      first: number | undefined,
      after: string | undefined
    ) {
      const response = await fetch(
        `https://${auth.store_name}.myshopify.com/admin/api/2026-10/graphql.json`,
        {
          method: "POST",
          headers: {
            "X-Shopify-Access-Token": auth.token,
            "Content-Type": "application/json",
            Accept: "application/json",
          },
          body: JSON.stringify({
            query: `query ($id: ID!, $namespace: String, $first: Int!, $after: String) { node(id: $id) { id ... on HasMetafields { metafields(namespace: $namespace, first: $first, after: $after) { nodes { id namespace key type value jsonValue createdAt updatedAt } pageInfo { hasNextPage endCursor } } } } }`,
            variables: {
              id: owner_id,
              namespace: namespace || undefined,
              first: first || 50,
              after: after || undefined,
            },
          }),
        }
      )
    
      if (!response.ok) {
        throw new Error(`${response.status} ${await response.text()}`)
      }
    
      const { data, errors } = await response.json()
      if (errors) {
        throw new Error(JSON.stringify(errors))
      }
      if (!data.node) {
        throw new Error(`No resource found for ${owner_id}`)
      }
    
      return data.node.metafields
    }
    

    Submitted by hugo989 3 hours ago