Add configuration to your location rule function
You can use metafields to store configuration values for your location rule function. Metafields provide greater flexibility to use functions, and are a prerequisite to creating a merchant user interface for configuring functions.
What you'll learn
Anchor link to section titled "What you'll learn"In this tutorial, you'll learn how to do the following tasks:
- Create a metafield definition.
- Add metafields to your GraphQL input query.
- Use metafield values in your function logic.
Requirements
Anchor link to section titled "Requirements"- You've completed the Getting started with building location rules tutorial.
Step 1: Create the metafield definition
Anchor link to section titled "Step 1: Create the metafield definition"To make your function reusable, you can replace hardcoded values in your function with metafield values.
For security reasons, it's recommended to create a metafield definition under a reserved namespace. The Shopify admin requires additional permissions to handle reserved namespaces in order to broker metafield changes on behalf of your application.
Update shopify.server.ts
file with the following code inside the afterAuth
hook to create a metafield definition and grant additional access to Shopify admin:
Your code should look like this:
Step 2: Configure the function
Anchor link to section titled "Step 2: Configure the function"After you create the metafield definition, you can update your function to use metafield values set by the user.
Update your input query to request a metafield value on the created location rule, which is the function owner for this function API. You can then use that value in your function logic.
Navigate to your function in
extensions/location-rule
.Replace the code in the
src/run.graphql
file with the following code.This update to the input query adds a metafield from the
locationRule
object, which is the function owner.The query differs slightly in Rust and JavaScript due to code generation requirements.
If you're using JavaScript, then run the following command to regenerate types based on your input query:
Replace the
src/run.rs
orsrc/run.js
file with the following code.This update includes parsing the JSON metafield value, and using values from that JSON in the function logic instead of hardcoded values.
This change is automatically reflected as long as you're running
dev
.
- Build a location rule user interface using Admin UI extensions.
- Learn how to use variables in your input query.