-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
44 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'> | ||
} |