t00-multiuser/server/objects/RequestCtx.ts

60 lines
1.6 KiB
TypeScript
Raw Normal View History

2024-09-19 00:41:40 +01:00
import { FastifyReply, FastifyRequest } from "fastify";
import SessionUser from "./SessionUser";
export default class RequestCtx {
public controllerName:string;
public actionName:string;
public session?:SessionUser;
public req: FastifyRequest;
public res: FastifyReply;
public constructor(req: FastifyRequest, res: FastifyReply, controllerName:string, actionName:string, sessionUser?:SessionUser) {
this.session = sessionUser;
this.req = req;
this.res = res;
this.controllerName = controllerName;
this.actionName = actionName;
}
view(view?:string | Object, model?: Object) {
let viewName: string = this.actionName;
let viewModel: Object = {};
if (typeof(view) === "string") {
viewName = view;
} else if (typeof(view) === "object") {
viewModel = view;
}
if (typeof(model) === "object") {
viewModel = model;
}
// @ts-ignore inject session
viewModel["session"] = this.session;
return this.res.view(`templates/${this.controllerName}/${viewName}.ejs`, viewModel);
}
// TODO: query params
redirectToAction(action:string, controller?:string) {
const controllerName = controller ?? this.controllerName;
if (action === "index") {
if (controllerName === "home") {
return this.res.redirect(302, `/`);
} else {
return this.res.redirect(302, `/${controllerName}`);
}
} else {
return this.res.redirect(302, `/${controllerName}/${action}`);
}
}
ok(message?:string) {
return this.res.status(200).send(message ?? "");
}
badRequest(message?:string) {
return this.res.status(400).send(message ?? "");
}
unauthorised(message?:string) {
return this.res.status(401).send(message ?? "");
}
}