ShopifySharp icon indicating copy to clipboard operation
ShopifySharp copied to clipboard

[Discussion] Best way to retrieve product variants by product ID

Open egillanton opened this issue 8 months ago • 2 comments

Description

I'm trying to retrieve product variants using a GraphQL query. Below is my current implementation in C# .NET Framework 4.6. It works, but I'm looking for the best practices and possible improvements to optimize performance.

Current Implementation

private List<ShopifySharp.ProductVariant> GetShopifyProductVariantsByProductId(string productId)
{
    if (string.IsNullOrWhiteSpace(productId))
    {
        throw new ArgumentException($"{nameof(productId)} cannot be null or empty");
    }

    bool hasNextPage = true;
    int first = 250;
    string cursor = null;

    List<ShopifySharp.ProductVariant> variants = new List<ShopifySharp.ProductVariant>();

    while (hasNextPage)
    {
        var variables = new Dictionary<string, object>
        {
            { "productId", productId },
            { "first", first }
        };

        if(cursor != null)
        {
            variables.Add("after", cursor);
        }

        var request = new GraphRequest
        {
            Query = @"
            query GetProductVariants($productId: ID!, $first: Int!, $after: String) {
              product(id: $productId) {
                id
                title
                variants(first: $first, after: $after) {
                  edges {
                    cursor
                    node {
                      id
                      title
                      sku
                    }
                  }
                  pageInfo {
                    hasNextPage
                  }
                }
              }
            }
            ",
            Variables = variables
        };

        GraphResult result = ExecRequest(_graphService.PostAsync(request));
        string jsonString = result.Json.ToString();
        JToken token = JToken.Parse(jsonString);
        List<ShopifySharp.ProductVariant> productVariants = token["product"]["variants"]["edges"].Select(v => v["node"].ToObject<ShopifySharp.ProductVariant>()).ToList();
        
        // Append product.Variants to variants
        variants.AddRange(productVariants);

        // Update cursor and hasNextPage
        hasNextPage = token["product"]["variants"]["pageInfo"]["hasNextPage"].ToObject<bool>();
        cursor = token["product"]["variants"]["edges"].Last()["cursor"].ToString();
    }

    return variants;
}

egillanton avatar Mar 11 '25 12:03 egillanton