Edits history of script submission #23762 for ' Create Custom Collection (shopify)'

  • bunnative
    One script reply has been approved by the moderators
    Ap­pro­ved
    //native
    
    /**
     * Create Custom Collection
     * Create a manual collection, optionally with an initial list of products (numeric IDs or GIDs). The collection is created unpublished; publish it to a sales channel to show it to customers.
     */
    export async function main(
      auth: RT.Shopify,
      title: string,
      product_ids: string[] | undefined,
      description_html: string | undefined,
      handle: string | undefined,
      image_url: string | undefined,
      sort_order:
        | "MANUAL"
        | "BEST_SELLING"
        | "ALPHA_ASC"
        | "ALPHA_DESC"
        | "PRICE_ASC"
        | "PRICE_DESC"
        | "CREATED"
        | "CREATED_DESC"
        | 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 ($collection: CollectionCreateInput!) { collectionCreate(collection: $collection) { collection { id legacyResourceId title handle descriptionHtml sortOrder productsCount { count } sources { id title } } userErrors { field message } } }`,
            variables: {
              collection: {
                title,
                descriptionHtml: description_html || undefined,
                handle: handle || undefined,
                image: image_url ? { src: image_url } : undefined,
                sortOrder: sort_order || undefined,
                sources: product_ids?.length
                  ? [
                      {
                        source: {
                          title,
                          inclusion: {
                            selections: product_ids.map((id) => ({
                              productId: id.startsWith("gid://")
                                ? id
                                : `gid://shopify/Product/${id}`,
                            })),
                          },
                        },
                      },
                    ]
                  : 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.collectionCreate.userErrors.length) {
        throw new Error(JSON.stringify(data.collectionCreate.userErrors))
      }
    
      return data.collectionCreate
    }
    

    Submitted by hugo989 3 hours ago