t00-multiuser/server/objects/RequestCtx.ts

67 lines
1.8 KiB
TypeScript
Raw Normal View History

2024-09-19 00:41:40 +01:00
import { FastifyReply, FastifyRequest } from "fastify";
import SessionUser from "./SessionUser";
2024-09-28 01:31:46 +01:00
import { UserLevel } from "../enums/UserLevel";
2024-09-19 00:41:40 +01:00
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;
2024-09-28 01:31:46 +01:00
// @ts-ignore inject enums
viewModel["UserLevel"] = UserLevel;
2024-09-28 10:32:33 +01:00
return this.res.view(`views/${this.controllerName}/${viewName}.ejs`, viewModel);
2024-09-19 00:41:40 +01:00
}
// TODO: query params
redirectToAction(action:string, controller?:string) {
const controllerName = controller ?? this.controllerName;
if (action === "index") {
if (controllerName === "home") {
return this.res.redirect(`/`, 302);
2024-09-19 00:41:40 +01:00
} else {
return this.res.redirect(`/${controllerName}`, 302);
2024-09-19 00:41:40 +01:00
}
} else {
return this.res.redirect(`/${controllerName}/${action}`, 302);
2024-09-19 00:41:40 +01:00
}
}
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 ?? "");
}
2024-09-26 00:47:08 +01:00
forbidden(message?:string) {
return this.res.status(403).send(message ?? "");
}
2024-09-19 00:41:40 +01:00
}