Re:Automatically generating types for Cloudflare Workers
by trevyn on Tuesday November 16, 2021 @07:03PM
(#29247882)
For those who don’t know, much of Serde’s magic is powered by Rust procedural derive macros, which generate (i.e. “derive”) code from a Rust struct definition.
You can, of course, write your own derive macros, and apply several derive macros to a single struct.
I wrote some to derive SQLite schemas and migrations and queries and auto-generate frontend TypeScript RPC code. So my source of truth is the Rust struct, and that sort of magically generates everything else.
I don’t know if this is a good idea, but it’s been pretty fun so far. :-)
There are also derive-macro-powered crates to do GraphQL, other flavors of SQL, WASM bindings, etc etc.
Re:Automatically generating types for Cloudflare Workers
by bobbylarrybobby on Tuesday November 16, 2021 @08:44PM
(#29248506)
Just to drive the point home, serde does solve the n^2 → 2n problem: serialized data is first deserialized to serde's intermediate data model (consisting of, like, 30 or so different types), from which a bespoke Rust object is produced. So you define how your types (de)serialize oblivious to the fact that serde_json, say, will be on the other end doing the actual (de)serialization.
(Correct me if I'm wrong about how Protocol Buffers work)
I think Serde is the closest thing I've seen to what I'm getting at; the way it can freely translate between XML and JSON and Rust structures without any help. But of course it's not a standalone schema language.