Skip to main content

Module json_resource

Module json_resource 

Source
Expand description

API resources: one place per type that decides how it appears as JSON.

Without this, every controller that returns a user decides for itself which columns to send, how to format the dates, and whether the password hash is included — and one of them will get it wrong. With it, a User has exactly one JSON shape, declared once:

pub struct UserResource;

impl JsonResource for UserResource {
    type Model = User;

    fn to_json(user: &User) -> Json {
        attributes()
            .set("id", user.id)
            .set("name", &user.name)
            .set("email", &user.email)
            .when(user.is_admin, "permissions", || Json::from(vec!["*"]))
            .when_some("avatar_url", user.avatar_url.as_deref())
            .finish()
    }
}

// In a controller:
UserResource::make(&user)                         // {"data": {…}}
UserResource::make(&user).created()               // 201
UserResource::collection(&users)                  // {"data": [{…}, …]}
UserResource::collection(&page.hydrate()?)
    .paginate(page.current_page, page.per_page, page.total)
    .path("/api/users")                           // + "meta" and "links"

The shapes are Laravel’s, down to the key names in meta and links, so a front end written against a Laravel API needs no changes.

Structs§

Attributes
An object under construction, with the conditionals a resource needs.
ResourceResponse
A resource on its way out: the data, whatever travels beside it, and the status it goes with.

Traits§

JsonResource
How a model becomes JSON. Implement it once per type that leaves the server.

Functions§

attributes
Start building the attributes of a resource.