Edits history of script submission #23721 for ' Create Product (shopify)'

  • bunnative
    One script reply has been approved by the moderators
    Ap­pro­ved
    //native
    
    /**
     * Create Product
     * Create a product, optionally with options (e.g. Size: S, M, L) and one variant per option combination. Each variant lists its option values in the same order as options. Without options, Shopify creates a single default variant. Image URLs are fetched by Shopify and attached as media.
     */
    export async function main(
      auth: RT.Shopify,
      title: string,
      description_html: string | undefined,
      vendor: string | undefined,
      product_type: string | undefined,
      tags: string[] | undefined,
      status: "DRAFT" | "ACTIVE" | "UNLISTED" | "ARCHIVED" | undefined,
      options: { name: string; values: string[] }[] | undefined,
      variants:
        | {
            option_values: string[]
            price?: string
            compare_at_price?: string
            sku?: string
          }[]
        | undefined,
      image_urls: 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: `mutation ($input: ProductSetInput!) { productSet(input: $input, synchronous: true) { product { id legacyResourceId title handle status vendor productType tags createdAt options { id name optionValues { id name } } variants(first: 100) { nodes { id legacyResourceId title sku price compareAtPrice selectedOptions { name value } inventoryItem { id } } } } userErrors { field message code } } }`,
            variables: {
              input: {
                title,
                descriptionHtml: description_html || undefined,
                vendor: vendor || undefined,
                productType: product_type || undefined,
                tags: tags?.length ? tags : undefined,
                status: status || undefined,
                productOptions: options?.length
                  ? options.map((o) => ({
                      name: o.name,
                      values: o.values.map((name) => ({ name })),
                    }))
                  : undefined,
                variants: variants?.length
                  ? variants.map((v) => ({
                      optionValues: v.option_values.map((name, i) => ({
                        optionName: options?.[i]?.name,
                        name,
                      })),
                      price: v.price || undefined,
                      compareAtPrice: v.compare_at_price || undefined,
                      sku: v.sku || undefined,
                    }))
                  : undefined,
                files: image_urls?.length
                  ? image_urls.map((originalSource) => ({
                      originalSource,
                      contentType: "IMAGE",
                    }))
                  : 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.productSet.userErrors.length) {
        throw new Error(JSON.stringify(data.productSet.userErrors))
      }
    
      return data.productSet
    }
    

    Submitted by hugo989 3 hours ago