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 = (a: T) => Promise>; abstract class ICoreHttpController { abstract url: string; public router = Router(); abstract call(): Routes; } export class CoreHttpController 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(req, res, this.routes["POST"]) ); } if (this.routes["DELETE"] != null) { this.router.delete(this.url, (req, res) => this.requestResponseController(req, res, this.routes["DELETE"]) ); } if (this.routes["PUT"] != null) { this.router.put( this.url, validationModelMiddleware(this.validationModel), (req, res) => this.requestResponseController(req, res, this.routes["PUT"]) ); } if (this.routes["GET"] != null) { this.router.get(this.url, (req, res) => this.requestResponseController(req, res, this.routes["GET"]) ); } return { router: this.router, }; } public put(usecase: CallBackFunction) { this.routes["PUT"] = usecase; } public delete(usecase: CallBackFunction) { this.routes["DELETE"] = usecase; } private async requestResponseController( req: Request, res: Response, usecase: CallBackFunction ) { 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) { this.routes["POST"] = usecase; } public get(usecase: CallBackFunction) { this.routes["GET"] = usecase; } }