FactuGES_ERP/apps/server/src/common/presentation/express/express-controller.ts

64 lines
1.8 KiB
TypeScript
Raw Normal View History

2025-02-01 21:48:13 +00:00
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<void | any>;
public execute(req: Request, res: Response, next: NextFunction): void {
this.req = req;
this.res = res;
this.next = next;
this.executeImpl();
}
protected ok<T>(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<T>(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 });
}
}