macro_rules! resource {
(
$resource:ident as $name:literal at $base:literal,
state: $state:ident,
schema: $schema:ident,
input: $input:ident,
id: $id:ident,
attributes: { $($field:ident : $ty:ty),* $(,)? }
$(, relationships: { $($rel:ident -> $arity:ident $target:literal),* $(,)? })?
$(,)?
) => { ... };
}http and validation only.Expand description
Declare a resource once: its schema, its serialization, and its parsing.
ash_jsonapi::resource! {
Todo as "todo" at "/todos",
state: App,
schema: TodoSchema,
input: NewTodo,
id: id,
attributes: { message: String, done: bool },
}That one declaration expands to everything you would otherwise write by hand:
struct TodoSchemaand itsSchemaimpl — the name, the base path, and the relationships.struct NewTodo, the parsed body, with a public field per attribute, plus itsFromRequestimpl: validate against the resource’s registered validator, then read each field.impl Resource<App> for Todo—NAME,PATH, and ato_resourcewriting every attribute and relationship.Todo::attributes_schema(), the JSON Schema for the attributes, built from each field’sAttributeimpl.
The field list appears once, so those four cannot drift apart. Field types
need Attribute — implemented already for
the standard scalars, Option<T> over them, and anything you implement it
on yourself.
The schema: and input: names are yours to pick. A macro_rules! macro
cannot build one identifier from another, so defaulting them to
TodoSchema/NewTodo would mean either a paste-style dependency in
every user’s tree or a companion proc-macro crate — more than two lines of
ceremony is worth. They are also the names you write when you reference
the generated types, so naming them here keeps that explicit.
TodoSchema and NewTodo are the conventional shapes.
§Relationships
ash_jsonapi::resource! {
Todo as "todo" at "/todos",
state: App,
schema: TodoSchema,
input: NewTodo,
id: id,
attributes: { message: String },
relationships: { owner -> one "user", tags -> many "tag" },
}Target type and arity are declared once and reach the linkage, both link
URLs, and the request schema. -> one reads a field holding one id;
-> many a field holding a collection of them. On the input struct a
to-one becomes Option<String> — absent linkage is not an error — and a
to-many becomes Vec<String>.
§What it does not write
The storage impls, and the validator’s registration. Where rows live is
yours: this writes the wire format, not your data layer. Pair it with
api! for the routes.
Need something it does not express — a computed attribute, an attribute whose name differs from its field, a body that is not JSON:API at all? Write the impls by hand. They are three ordinary traits, and this is shorthand for the common shape rather than the only way in.