Rust support in Shopify Functions
You can write your functions in Rust. This guide describes the Rust crate that Shopify provides to help developers build with Shopify Functions.
Requirements
Anchor link to section titled "Requirements"You need to have graphql_client
installed as a dependency in your project:
How it works
Anchor link to section titled "How it works"Rust crate bundles graphql_client
-based type generation, reduces boilerplate code, and makes it easier to unit testing various function inputs. Rust crate includes the following components:
Component | Description |
---|---|
generate_types |
A macro that enables you to do the following:
|
shopify_function |
An attribute macro that marks the following function as the entry point for a function. It manages the function's STDIN input parsing and STDOUT output serialization for you. |
run_function_with_input |
A utility for unit testing that enables you to add new tests based on a given JSON input string. |
Viewing the generated types
Anchor link to section titled "Viewing the generated types"To preview the types generated by the generate_types
macro, use the cargo doc
command.
You can also use the cargo-expand crate to view the generated source, or use the rust-analyzer VSCode extension to get IntelliSense for Rust and the generated types.
Example implementation
Anchor link to section titled "Example implementation"Explore an example implementation of Shopify Function Rust crate.
Update an existing function
Anchor link to section titled "Update an existing function"You can update an existing function written in Rust to use the shopify_function
attribute:
In your project, run
cargo add shopify_function
.Run
cargo add graphql_client@0.12.0
.Delete
src/api.rs
.In
main.rs
, complete the following steps:Add imports for
shopify_function
:Remove references to
mod api
.Add type generation directly under your imports:
Remove the
main
function entirely.Attribute the
function
function with theshopify_function
macro, and change its return type:Update the types and fields utilized in the function to the new, auto-generated structs. The following table provides an example:
Old New input::Input
input::ResponseData
input::Metafield
input::InputDiscountNodeMetafield
input::DiscountNode
input::InputDiscountNode
FunctionResult
output::FunctionResult
DiscountApplicationStrategy::First
output::DiscountApplicationStrategy::FIRST
Add
.output.graphql
to your.gitignore
file.
- Explore the reference documentation for crate
shopify_function
.