import { NextFunction, Request, Response } from "express"; import httpStatus from "http-status"; export abstract class ExpressController { protected req!: Request; protected res!: Response; protected next!: NextFunction; protected abstract executeImpl(): Promise; public execute(req: Request, res: Response, next: NextFunction): void { this.req = req; this.res = res; this.next = next; this.executeImpl(); } protected ok(dto?: T) { return dto ? this.res.status(httpStatus.OK).json(dto) : this.res.status(httpStatus.OK).send(); } protected fail(error: string | Error) { console.error("ExpressController FAIL:", error); return this.res .status(httpStatus.INTERNAL_SERVER_ERROR) .json({ message: error instanceof Error ? error.message : error }); } protected created(dto?: T) { return dto ? this.res.status(httpStatus.CREATED).json(dto) : this.res.status(httpStatus.CREATED).send(); } protected noContent() { return this.res.status(httpStatus.NO_CONTENT).send(); } protected clientError(message?: string) { return this.res.status(httpStatus.BAD_REQUEST).json({ message }); } protected unauthorizedError(message?: string) { return this.res.status(httpStatus.UNAUTHORIZED).json({ message }); } protected forbiddenError(message?: string) { return this.res.status(httpStatus.FORBIDDEN).json({ message }); } protected notFoundError(message?: string) { return this.res.status(httpStatus.NOT_FOUND).json({ message }); } protected conflictError(message?: string) { return this.res.status(httpStatus.CONFLICT).json({ message }); } protected invalidInputError(message?: string) { return this.res.status(httpStatus.UNPROCESSABLE_ENTITY).json({ message }); } }