Skip to main content

domain_api

Macro domain_api 

Source
macro_rules! domain_api {
    (
        $resource:ident as $name:literal at $base:literal,
        state: $state:ident,
        operations: [$($op:tt)+]
        $(,)?
    ) => { ... };
}
Available on crate feature domain only.
Expand description

Serve an ash-domain resource over JSON:API.

The ash-domain counterpart to resource!: where that derives everything from a field list you write, this derives it from the schema the domain already holds. Nothing about the resource is restated — attributes, types, relationships and their cardinality all come from #[derive(Resource)].

ⓘ
ash_jsonapi::domain_resource! {
    Todo as "todo" at "/todos",
    state: App,
}

ash_jsonapi::api! {
    operations: [ash_jsonapi::CRUD],
    resource: Todo, name: "todo", path: "/todos", state: App,
}

App implements DomainState; this writes Resource, Storage and the five operation traits in terms of it, so api! serves a domain resource exactly as it serves a hand-rolled one.

Every action runs through Bound rather than around it, so policies, extensions and domain validation all apply. A Forbidden becomes 403, an Invalid a 422 pointing at the field, and a data-layer failure an opaque 500 — see error_from. A domain resource and its routes, from one declaration.

domain_resource! writes the traits and api! the routes, and both need the same name, path and state. Writing them twice is three chances for the two to disagree — and a mismatched name is not a compile error, it is a resource that serializes as one type and validates as another.

ⓘ
ash_jsonapi::domain_api! {
    Todo as "todo" at "/todos",
    state: App,
    operations: [ash_jsonapi::CRUD],
}

Exactly equivalent to the two macros written out, with each fact stated once:

ⓘ
ash_jsonapi::domain_resource! {
    Todo as "todo" at "/todos",
    state: App,
}

ash_jsonapi::api! {
    operations: [ash_jsonapi::CRUD],
    resource: Todo, name: "todo", path: "/todos", state: App,
}

Use the two directly when they need to diverge — a resource served at two paths, or one whose traits you write by hand.