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§
Sourcefn to_resource(&self, req: &Request) -> Value
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§
Sourcefn to_response(&self, req: &Request) -> HttpResponse
fn to_response(&self, req: &Request) -> HttpResponse
Return a JSON HTTP response with the resource data.
Sourcefn to_wrapped_response(&self, req: &Request) -> HttpResponse
fn to_wrapped_response(&self, req: &Request) -> HttpResponse
Return a JSON HTTP response wrapped in {"data": ...} envelope.