Can the #typegen macro be used with serde?

With the new #typegen and #query macros in the shopify_function crate, is there any way at all to pass additional #[derive()] macros to the generated types? To my understanding, you can’t, which really limits where you can use the auto-generated types.

Currently, the #typegen macro is incompatible with my requirements, so I’m using:

  • Handwritten custom structs that match the Discount Function API input schema
  • serde_json for serialization to JSON
  • Custom code generator for JSON parsing (to reduce code size bloat)

For example, my app has a feature where the calculated Vec<ProductDiscountCandidate> is serialized to JSON (using serde_json) as a field of a custom struct:

/// A JSON object that contains the results of a discount visit.
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
pub struct VisitDiscountJsonResult {
    pub discounts: Vec<ProductDiscountCandidate>,
    pub metadata: VisitDiscountMetadata,
}

With the new #typegen, since there is no way for me to add serde::Serialize to the generated types, I would have to manually implement the serde::Serialize trait for each type, which defeats the purpose of code generation.

I would like to use the new WASM Query API to reduce JSON parsing overhead in my Functions, but my code also runs in other contexts where the Query API doesn’t exist. Right now, it’s looking like the only way to make this work is going to be to implement the shopify_function_wasm_api::{Serialize, Deserialize} traits manually (or with a custom code generator).

Thanks,
Tobe

Hi @tobebuilds

I’ve connected with the relevant team to see what they would recommend!

1 Like

asked here: https://shopify.slack.com/archives/C03JZK7E11R/p1750148545975889

Hi again @tobebuilds

There’s no current plan to add support for this. However it would be useful to understand more as to what exactly you’re doing outside of the query API and why you’d need this functionality?

Hi Liam,

My app has a “Test discounts” feature that allows users to preview what discounts would be applied based on the items in the cart. It takes a Discount Functions API Input as its input and returns the VisitDiscountJsonResult structure I included in my original post.

It’s not a WebAssembly binary. It’s a normal executable implemented in Rust. In order to communicate with the process that calls it, it reads JSON from stdin and writes JSON to stdout. I’m currently using serde to serialize VisitDiscountJsonResult to JSON.

Ideally, I could use both Shopify’s and serde’s Serialize traits on the same types. But I can’t, because Shopify’s Serialize trait doesn’t support my types (it doesn’t support enums).

Right now, I think the best way forward will be:

  1. Use #typegen to auto-generate WASM Query API-compatible types from my input query.
  2. Manually implement serde’s Serialize trait for any types I’m serializing to JSON.

Best,
Tobe