Transform your models and data objects into standardized JSON responses. Perfect for building consistent APIs.
Transform your models into JSON responses.
Automatically handle arrays of resources.
Embed nested resources easily.
Extend `JsonResource` and define the `toArray` method to control the output format.
1import { JsonResource } from "canxjs";23export class UserResource extends JsonResource {4toArray(request) {5return {6id: this.id,7name: this.name,8email: this.email,9created_at: this.created_at,10// Computed or conditional attributes11is_admin: this.role === 'admin'12};13}14}
Return resources directly from your controllers or route handlers. CanxJS handles the serialization.
1import { UserResource } from "./resources/UserResource";23app.get("/user/:id", async (req, res) => {4const user = await User.find(req.params.id);56// Return single resource7return new UserResource(user);8});910app.get("/users", async (req, res) => {11const users = await User.all();1213// Return collection14return UserResource.collection(users);15});
Include related resources or hide data based on conditions using helper methods.
1// In PostResource.ts2export class PostResource extends JsonResource {3toArray(request) {4return {5id: this.id,6title: this.title,7content: this.content,8// Nesting user resource9author: new UserResource(this.author),10// Conditional Relationship11comments: this.whenLoaded('comments', () => CommentResource.collection(this.comments)),12};13}14}