Skip to content

Commit

Permalink
basic class of controller
Browse files Browse the repository at this point in the history
  • Loading branch information
pestsov-v committed Feb 15, 2022
1 parent 043fd17 commit 8f5d6d4
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
37 changes: 37 additions & 0 deletions src/common/base.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { Response, Router } from "express";
import { LoggerService } from "../logger/logger.service";
import { IControllerRoute } from "./route.interface";
export {Router} from 'express';

export abstract class BaseController {
private readonly _router: Router;

constructor(private logger: LoggerService) {
this._router = Router();
}

get router() {
return this._router;
}

public send<T>(res: Response, code: number, message: T) {
res.type('application/json');
return res.status(code).json(message);
}

public ok<T>(res: Response, message: T) {
return this.send<T>(res, 200, message)
}

public created(res: Response) {
return res.sendStatus(201);
}

protected bindRoutes(routes: IControllerRoute[]) {
for(const route of routes) {
this.logger.log(`[${route.method}: ${route.path}`);
const handler = route.func.bind(this);
this.router[route.method](route.path, handler);
}
}
}
7 changes: 7 additions & 0 deletions src/common/route.interface.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { Request, Response, NextFunction, Router } from "express";

export interface IControllerRoute {
path: string;
func: (req: Request, res: Response, next: NextFunction) => void;
method: keyof Pick<Router, 'get' | 'post' | 'delete' | 'patch' | 'put'>
}

0 comments on commit 8f5d6d4

Please sign in to comment.