Skip to main content

Compute input query variables at runtime

Use input query variables to pass arguments into a function's input query. Their values come from a metafield on the function owner. Every function run reads the same values, so the input query can't select data based on the current cart.

A prepare target removes that limit. It runs just before the run target, reads data from the cart, and returns the values for the run target's input query variables.

In this guide, you'll add a prepare target to a cart and checkout validation function. The prepare target reads the buyer's country, and the run target uses it to load the one app-owned metaobject entry that holds the quantity limit for that country.


When a function has a prepare target, Shopify does the following for each function run:

  1. Takes the variables object that the prepare target returns. Each key is the name of a variable that the run target's input query declares.
  2. Runs the run target's input query with those variables and passes the result to the run target as its input.

The prepare target's input query can request the same fields as the run target's input query, except the fields that only run targets can request, such as fetchResult. It can't declare variables. If the prepare target fails, then the run target doesn't execute and the function run fails.



Anchor to Step 1: Add the prepare target to your configurationStep 1: Add the prepare target to your configuration

In your function's shopify.extension.toml file, add a [[extensions.targeting]] section for the prepare target, next to the section for the run target. The prepare target needs its own input query file and export:

shopify.extension.toml

shopify.extension.toml

[[extensions.targeting]]
target = "cart.validations.generate.prepare"
input_query = "src/cart_validations_generate_prepare.graphql"
export = "cart-validations-generate-prepare"

[[extensions.targeting]]
target = "cart.validations.generate.run"
input_query = "src/cart_validations_generate_run.graphql"
export = "cart-validations-generate-run"
[[extensions.targeting]]
target = "cart.validations.generate.prepare"
input_query = "src/cart_validations_generate_prepare.graphql"
export = "cart_validations_generate_prepare"

[[extensions.targeting]]
target = "cart.validations.generate.run"
input_query = "src/cart_validations_generate_run.graphql"
export = "cart_validations_generate_run"

The prepare target supplies the run target's variables, so don't set input_variables on the prepare target or the run target. If your configuration has an [extensions.input.variables] section, then remove it. Shopify rejects a deploy that configures variables in either place. Other targets of your function can keep their own input_variables. A run target can have a fetch target or a prepare target before it, but not both.

Then, download the latest schema so that code generation includes the prepare target:

Terminal

shopify app function schema

Anchor to Step 2: Write the prepare input queryStep 2: Write the prepare input query

Create the src/cart_validations_generate_prepare.graphql file. This query reads the buyer's country:

src/cart_validations_generate_prepare.graphql

query CartValidationsGeneratePrepareInput {
localization {
country {
isoCode
}
}
}

The prepare target's input query can't declare variables. If a field in this query takes arguments, then write their values directly in the query.

If you're using JavaScript, then regenerate types for the new query:

Terminal

shopify app function typegen

Anchor to Step 3: Return the run target's variablesStep 3: Return the run target's variables

Create the prepare function. It returns the buyer's country code in lowercase as the ruleSetHandle variable:

Prepare function

src/cart_validations_generate_prepare.js

// @ts-check

/**
* @typedef {import("../generated/api").CartValidationsGeneratePrepareInput} CartValidationsGeneratePrepareInput
* @typedef {import("../generated/api").CartValidationsGeneratePrepareResult} CartValidationsGeneratePrepareResult
*/

/**
* @param {CartValidationsGeneratePrepareInput} input
* @returns {CartValidationsGeneratePrepareResult}
*/
export function cartValidationsGeneratePrepare(input) {
return {
variables: {
ruleSetHandle: input.localization.country.isoCode.toLowerCase(),
},
};
}
use crate::schema;
use shopify_function::prelude::*;
use shopify_function::Result;

#[shopify_function]
fn cart_validations_generate_prepare(
input: schema::prepare::CartValidationsGeneratePrepareInput,
) -> Result<schema::CartValidationsGeneratePrepareResult> {
Ok(schema::CartValidationsGeneratePrepareResult {
variables: schema::run::CartValidationsGenerateRunInputVariables {
rule_set_handle: input.localization().country().iso_code().to_lowercase(),
},
})
}

The value of variables must be a JSON object. If the prepare target returns any other value, then the function run fails with an InvalidOutputError. The object needs a key for each required variable of the run target's input query. A required variable has a non-null type, such as String!, and no default value. The object can leave out an optional variable.

In Rust, variables is the CartValidationsGenerateRunInputVariables struct, which the shopify_function crate generates from the variables that the run target's input query declares. You declare $ruleSetHandle in that query in the next step. If you later add, remove, rename, or change the type of a variable in the run target's input query, then the prepare function doesn't compile until you update it.

Export the prepare function alongside the run function. In Rust, the custom_scalar_overrides option of typegen sets the type of the prepare result's variables field to the run target's variables struct:

Entry points

src/index.js

export * from './cart_validations_generate_prepare';
export * from './cart_validations_generate_run';
use shopify_function::prelude::*;
use std::process;

pub mod cart_validations_generate_prepare;
pub mod cart_validations_generate_run;

#[typegen("./schema.graphql", custom_scalar_overrides = {
"CartValidationsGeneratePrepareResult.variables" => run::CartValidationsGenerateRunInputVariables,
})]
pub mod schema {
#[query("src/cart_validations_generate_prepare.graphql")]
pub mod prepare {}

#[query("src/cart_validations_generate_run.graphql")]
pub mod run {}
}

fn main() {
log!("Please invoke a named export.");
process::abort();
}

Anchor to Step 4: Use the variables in the run input queryStep 4: Use the variables in the run input query

Declare the variable in the run target's input query, and use it as a field argument. This query loads the metaobject entry whose handle matches ruleSetHandle. You create the metaobject entries in step 5.

src/cart_validations_generate_run.graphql

query CartValidationsGenerateRunInput($ruleSetHandle: String!) {
cart {
lines {
quantity
}
}
shop {
ruleSet: metaobject(handle: {type: "$app:validation_rule_set", handle: $ruleSetHandle}) {
maxQuantity: field(key: "max_quantity") {
jsonValue
}
}
}
}

Shopify checks the variables that the prepare target returns against this query. If a value has the wrong type, a required variable is missing, or the prepare target returns a variable that this query doesn't declare, then the function run fails with an InvalidVariableValueError.

If you're using JavaScript, then regenerate types for the updated query:

Terminal

shopify app function typegen

Update the run function to read the limit from the metaobject entry. If no entry has a matching handle, then ruleSet is null and the function doesn't apply a limit:

Run function

src/cart_validations_generate_run.js

// @ts-check

/**
* @typedef {import("../generated/api").CartValidationsGenerateRunInput} CartValidationsGenerateRunInput
* @typedef {import("../generated/api").CartValidationsGenerateRunResult} CartValidationsGenerateRunResult
*/

/**
* @param {CartValidationsGenerateRunInput} input
* @returns {CartValidationsGenerateRunResult}
*/
export function cartValidationsGenerateRun(input) {
const errors = [];
const maxQuantity = input.shop.ruleSet?.maxQuantity?.jsonValue;

if (typeof maxQuantity === 'number') {
const totalQuantity = input.cart.lines.reduce(
(total, line) => total + line.quantity,
0,
);

if (totalQuantity > maxQuantity) {
errors.push({
message: `You can't order more than ${maxQuantity} items.`,
target: '$.cart',
});
}
}

return {operations: [{validationAdd: {errors}}]};
}
use crate::schema;
use shopify_function::prelude::*;
use shopify_function::scalars::JsonValue;
use shopify_function::Result;

#[shopify_function]
fn cart_validations_generate_run(
input: schema::run::CartValidationsGenerateRunInput,
) -> Result<schema::CartValidationsGenerateRunResult> {
let mut errors = Vec::new();

let max_quantity = input
.shop()
.rule_set()
.and_then(|rule_set| rule_set.max_quantity())
.and_then(|field| match field.json_value() {
Some(JsonValue::Number(max)) => Some(*max as i32),
_ => None,
});

if let Some(max_quantity) = max_quantity {
let total_quantity: i32 = input.cart().lines().iter().map(|line| *line.quantity()).sum();

if total_quantity > max_quantity {
errors.push(schema::ValidationError {
message: format!("You can't order more than {max_quantity} items."),
target: "$.cart".to_string(),
});
}
}

Ok(schema::CartValidationsGenerateRunResult {
operations: vec![schema::Operation::ValidationAdd(
schema::ValidationAddOperation { errors },
)],
})
}

Anchor to Step 5: Deploy the function and create the rule setsStep 5: Deploy the function and create the rule sets

The run target reads its quantity limit from an app-owned metaobject entry. In your app's shopify.app.toml file, create a metaobject definition with an integer field for the limit:

shopify.app.toml

[metaobjects.app.validation_rule_set]
name = "Validation rule set"

[metaobjects.app.validation_rule_set.fields.max_quantity]
name = "Max quantity"
type = "number_integer"

Deploy your app. The deploy includes the function and the metaobject definition:

Terminal

shopify app deploy

Shopify rejects the deploy if the configuration breaks a prepare target rule. For example, the prepare target's input query can't declare variables, and the run target's input query must declare at least one variable. The deploy can't check which variables the prepare target returns, so Shopify checks them when the function runs.

After the deploy succeeds, create an entry of the type $app:validation_rule_set for each country that has its own limit. Each entry's handle is the country's two-letter code in lowercase, which is the value that the prepare target returns.

The $app prefix refers to the app that makes the request, so create the entries as your app. In a dev store, you can use shopify app execute, which authenticates as your app. For example, the following command creates an entry that limits carts in Canada to five items:

Terminal

shopify app execute --query 'mutation {
metaobjectCreate(metaobject: {
type: "$app:validation_rule_set"
handle: "ca"
fields: [{ key: "max_quantity", value: "5" }]
}) {
userErrors {
field
message
}
}
}'

When your function runs on a store, the Logs section of your Dev Dashboard shows one entry for the prepare target and one entry for the run target. The prepare target's entry has the earlier time, and its Output shows the variables object. The run target's entry shows the same values under Input query variables. In each entry, the Related runs row links to the other entry, with the text Prepare log or Run log.



Was this page helpful?