Custom discount functions - can we dynamically update the query?

We have a headless store, with a CMS used as the source of truth for product data and other content.

We want to expand our range of discounting features, including customised tiered discounts on selected products (by tags and/or groups of tags), automatic bundle creation, and gifts with purchase. We had previously been using lineItem scripts to handle these, and now must migrate to functions.

We see this as an opportunity to move on from having to maintain the discounting in two separate places (the CMS for the storefront and the lineItem scripts for the checkout). Ideally, we would define the discounts in our CMS and dynamically map them onto a function that implements the discounts at checkout.

The problem I have is that I’m unsure of the best way to approach this. The function can obviously query the CMS for the latest discount config, but the graphql query in the function is fixed in a file, so we can’t dynamically update the arguments in that query - for example, updating the array of tag strings in the hasAnyTag field of a product variant.

What is the best approach here? Do we have to simply request all products and do the sorting in the function? Or can we be more granular in controlling the shape of our query?

Hi Bobstacle,

You can’t dynamically update the query of a Shopify Function. Instead, you need to use input variables in your query:

https://shopify.dev/docs/apps/build/functions/input-output/use-variables-input-queries

These input variables can be read from metafields at the time of function execution, which is how you can provide dynamic parameters to a Function.

Best,

Tobe

Thanks Tobe - that looks like a good approach for our requirements.

Hi Tobebuilds, I’m wondering if we can use dynamic variable input without fixing it in toml file like this

query RunInput($timestamp: DateTimeWithoutTimezone!) {
  buyerJourney {
    step
  }
  shop {
    localTime {
      dateTimeAfter(dateTime: $timestamp)
    }
  }
}

toml file:

[extensions.input.variables]
namespace = "$app:validation-function"
key = "timestamp"