Controller
Pashmak can accept both function and class controllers
functional Controllers
Class Controllers
import { db, storage, logger } from "@devbro/pashmak/facades";
import { ctx } from "@devbro/pashmak/context";
import {
Request,
Response,
Model,
Param,
ValidatedRequest,
BaseController,
Controller,
Get,
Post,
} from "@devbro/pashmak/router";
@Controller("/api/v1/cats", {
middlewares: [mid1, mid2],
})
export class CatController extends BaseController {
@Get({ middlewares: [logResponseMiddleware] })
async show() {
const r = await db().runQuery({ sql: "select * from cats", bindings: [] });
return {
message: "GET cats",
data: r,
};
}
@Post()
async store() {
const req = ctx().get<Request>("request");
logger().info({ msg: "request details", body: req.body, files: req.files });
return "success";
}
@Put("/:id")
async update(@Param("id") id, @Model(CatModel, "id", "id") cat: CatModel) {
return "success";
}
@Get({ path: "/file" })
async getFile() {
const res = ctx().get<Response>("response");
await res.writeHead(200, {
"Content-Type": "image/jpeg",
});
(await storage().getStream("test.jpg")).pipe(res);
}
@Get({ path: "/file-details" })
async getFileDetails() {
return await storage().metadata("test.jpg");
}
@Get({ path: "/:id/notes/:noteId" })
showById(@Param("noteId") noteId: string, @Param("id") id: string) {
return "notes";
}
}
class decorators
@Model( ModelClass , param_name , model_field )
automatically fetches a model instance based on a route parameter and injects it into the controller method.
param_name is optional and defaults to "id". it is the param name in the url.
model_field is optional and defaults to "id". it is the field in the model to be matched against the param value.
@Param( param_name )
extracts a specific parameter from the request URL and injects it into the controller method. If param was not defined in url, it will be undefined.
@ValidatedRequest( validation_schema )
validates the incoming request data against a defined schema and injects the validated data into the controller.
validation_schema can be a yup yup.ObjectSchema or a function that returns yup.ObjectSchema.
order of middleware execution
the order is as followed:
- middleswares defined in router as globalmiddlewares
- middlewares defined at controller class
- middlewares defined at each method