Edits history of script submission #23722 for ' Update Product (shopify)'

  • bunnative
    One script reply has been approved by the moderators
    Ap­pro­ved
    //native
    
    /**
     * Update Product
     * Update a product's fields. Only the fields you fill in are changed; tags, when given, replace all existing tags (use Add Tags / Remove Tags to edit them incrementally).
     */
    export async function main(
      auth: RT.Shopify,
      product_id: string,
      title: string | undefined,
      description_html: string | undefined,
      vendor: string | undefined,
      product_type: string | undefined,
      tags: string[] | undefined,
      status: "DRAFT" | "ACTIVE" | "UNLISTED" | "ARCHIVED" | undefined,
      handle: string | undefined,
      seo_title: string | undefined,
      seo_description: string | undefined
    ) {
      const id = product_id.startsWith("gid://")
        ? product_id
        : `gid://shopify/Product/${product_id}`
    
      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: `mutation ($product: ProductUpdateInput!) { productUpdate(product: $product) { product { id legacyResourceId title handle status vendor productType tags descriptionHtml updatedAt seo { title description } } userErrors { field message } } }`,
            variables: {
              product: {
                id,
                title: title || undefined,
                descriptionHtml: description_html || undefined,
                vendor: vendor || undefined,
                productType: product_type || undefined,
                tags: tags?.length ? tags : undefined,
                status: status || undefined,
                handle: handle || undefined,
                seo:
                  seo_title || seo_description
                    ? {
                        title: seo_title || undefined,
                        description: seo_description || undefined,
                      }
                    : 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.productUpdate.userErrors.length) {
        throw new Error(JSON.stringify(data.productUpdate.userErrors))
      }
    
      return data.productUpdate
    }
    

    Submitted by hugo989 3 hours ago