Edits history of script submission #23736 for ' Search Product Variants (shopify)'

  • bunnative
    One script reply has been approved by the moderators
    Ap­pro­ved
    //native
    
    /**
     * Search Product Variants
     * Search product variants across all products with Shopify's search syntax (e.g. `sku:ABC-1`, `barcode:0123`, `product_id:123`, `title:Large`, `inventory_quantity:<5`). Leave query empty to list all variants. Returns one page; pass pageInfo.endCursor as after for the next.
     */
    export async function main(
      auth: RT.Shopify,
      query: string | undefined,
      sort_key:
        | "SKU"
        | "TITLE"
        | "FULL_TITLE"
        | "NAME"
        | "POSITION"
        | "INVENTORY_QUANTITY"
        | "POPULAR"
        | "ID"
        | "RELEVANCE"
        | undefined,
      reverse: boolean | 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 ($first: Int!, $after: String, $query: String, $sortKey: ProductVariantSortKeys, $reverse: Boolean) { productVariants(first: $first, after: $after, query: $query, sortKey: $sortKey, reverse: $reverse) { nodes { id legacyResourceId title displayName sku price compareAtPrice position inventoryQuantity inventoryPolicy availableForSale createdAt updatedAt selectedOptions { name value } barcodes(first: 5) { nodes { value type } } inventoryItem { id tracked } product { id title handle status } } pageInfo { hasNextPage endCursor } } }`,
            variables: {
              first: first || 50,
              after: after || undefined,
              query: query || undefined,
              sortKey: sort_key || undefined,
              reverse: reverse || 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))
      }
    
      return data.productVariants
    }
    

    Submitted by hugo989 3 hours ago