webstudio/server/src/core/controllers/http_controller.ts
2023-10-31 09:03:39 +00:00

107 lines
2.6 KiB
TypeScript

import { validationModelMiddleware } from "../middlewares/validation_model";
import { Result } from "../helper/result";
import { Router, Request, Response } from "express";
import { IRouteModel, Routes } from "../interfaces/router";
export type CallBackFunction<T> = (a: T) => Promise<Result<any, any>>;
abstract class ICoreHttpController {
abstract url: string;
public router = Router();
abstract call(): Routes;
}
export class CoreHttpController<V> implements ICoreHttpController {
url: string;
validationModel: any;
routes = {
POST: null,
GET: null,
DELETE: null,
PUT: null,
};
public router = Router();
constructor(routerModel: IRouteModel) {
this.url = "/" + routerModel.url;
this.validationModel = routerModel.validationModel;
}
call(): Routes {
if (this.routes["POST"] != null) {
this.router.post(
this.url,
validationModelMiddleware(this.validationModel),
(req, res) =>
this.requestResponseController<V>(req, res, this.routes["POST"])
);
}
if (this.routes["DELETE"] != null) {
this.router.delete(this.url, (req, res) =>
this.requestResponseController<V>(req, res, this.routes["DELETE"])
);
}
if (this.routes["PUT"] != null) {
this.router.put(
this.url,
validationModelMiddleware(this.validationModel),
(req, res) =>
this.requestResponseController<V>(req, res, this.routes["PUT"])
);
}
if (this.routes["GET"] != null) {
this.router.get(this.url, (req, res) =>
this.requestResponseController<V>(req, res, this.routes["GET"])
);
}
return {
router: this.router,
};
}
public put(usecase: CallBackFunction<V>) {
this.routes["PUT"] = usecase;
}
public delete(usecase: CallBackFunction<V>) {
this.routes["DELETE"] = usecase;
}
private async requestResponseController<T>(
req: Request,
res: Response,
usecase: CallBackFunction<T>
) {
let payload = null;
if (req["model"] != undefined) {
payload = req.body as T;
}
if (req.query.page !== undefined) {
payload = String(req.query.page);
}
if (req.query.id !== undefined) {
payload = String(req.query.id);
}
(await usecase(payload)).fold(
(ok) => {
res.json(ok);
return;
},
(err) => {
res.status(400).json(err);
return;
}
);
}
public post(usecase: CallBackFunction<V>) {
this.routes["POST"] = usecase;
}
public get(usecase: CallBackFunction<V>) {
this.routes["GET"] = usecase;
}
}