Rust for Functions
You can write your functions in Rust. This guide describes the shopify_function
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"The shopify_function
Rust crate bundles graphql_client
-based type generation, reduces boilerplate code, and makes it easier to test various function inputs. It includes the following components:
Component | Description |
---|---|
shopify_function_target |
An attribute macro that transforms the following function to:
|
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 shopify_function
Rust crate, 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 implementations
Anchor link to section titled "Example implementations"Explore example implementations using the shopify_function
Rust crate.
For API versions 2023-07 and earlier, the generate_types
and shopify_function
macros can be used directly to conform to previous WebAssembly requirements.
Binary size tips
Anchor link to section titled "Binary size tips"Shopify Functions compiled Wasm file must be under 256 kB. Here are a few tips to keep binary size small when using Rust:
Update the
shopify_function
crate to the latest version.For regular expressions, use the regex_lite crate.
Follow tips and documentation in the johnthagen/min-sized-rust GitHub repository.
Use
wasm-snip
to remove the panicking code, thenwasm-opt
to strip debug information. For example:Use
to_ascii_uppercase
andto_ascii_lowercase
when possible to avoid pulling in Unicode tables, unless needed.Only query for data you need.
Code generation happens for all types and fields included in the input queries (for example,
run.graphql
). Review and remove any unused parts of the queries.Keep JSON metafields that require deserialization as small as possible.
Code generated for deserialization increases the binary size. The smaller the metafield is, the less code needs to be generated.
Bring your own types and deserializers.
Instead of using the generated structs from the
shopify_function_macro
crate, write the appropropriate struct definitions and derive the deserializsers usingmini_serde
.The structs from
shopify_function_macro
can be used as a starting point, see them withcargo expand
.Alternative serializers are generally less efficient than serde, make sure to benchmark the instruction count when going down this path.
- Explore the reference documentation for the
shopify_function
Rust crate.