Skip to main content

Resource

Trait Resource 

Source
pub trait Resource {
    // Required method
    fn to_resource(&self, req: &Request) -> Value;

    // Provided methods
    fn to_response(&self, req: &Request) -> HttpResponse { ... }
    fn to_wrapped_response(&self, req: &Request) -> HttpResponse { ... }
    fn collection(items: &[Self], req: &Request) -> Vec<Value>
       where Self: Sized { ... }
    fn to_response_with(&self, req: &Request, additional: Value) -> HttpResponse { ... }
}
Expand description

Trait for transforming models into JSON API responses.

Implement this trait on resource structs to define how models are serialized for API consumers. The Request parameter enables context-dependent field selection (e.g., based on auth or roles).

§Example

use ferro_rs::{Resource, ResourceMap, Request};
use serde_json::json;

struct UserResource {
    id: i32,
    name: String,
    email: String,
}

impl Resource for UserResource {
    fn to_resource(&self, _req: &Request) -> serde_json::Value {
        ResourceMap::new()
            .field("id", json!(self.id))
            .field("name", json!(self.name))
            .field("email", json!(self.email))
            .build()
    }
}

Required Methods§

Source

fn to_resource(&self, req: &Request) -> Value

Transform this into a JSON value for API responses. Request is available for context-dependent field selection (auth, roles, etc).

Provided Methods§

Source

fn to_response(&self, req: &Request) -> HttpResponse

Return a JSON HTTP response with the resource data.

Source

fn to_wrapped_response(&self, req: &Request) -> HttpResponse

Return a JSON HTTP response wrapped in {"data": ...} envelope.

Source

fn collection(items: &[Self], req: &Request) -> Vec<Value>
where Self: Sized,

Map a slice of resources to their JSON representations.

Convenience for items.iter().map(|item| item.to_resource(req)).collect().

§Example
let users: Vec<UserResource> = /* ... */;
let json_array = UserResource::collection(&users, &req);
// Returns: Vec<serde_json::Value>
Source

fn to_response_with(&self, req: &Request, additional: Value) -> HttpResponse

Return a wrapped response with additional top-level fields merged.

§Example
let response = resource.to_response_with(&req, json!({"meta": {"version": "v1"}}));
// Output: {"data": {...}, "meta": {"version": "v1"}}

Implementors§