import { All, Body, Controller, Delete, Get, Headers, HttpStatus, Next, Param, Post, Put, Query, Req, RequestMethod, Res, UnauthorizedException } from "@nestjs/common"; import { Response, Request } from "express"; import * as jwt from "jsonwebtoken"; import { QueryDto } from "../dtos/query.dto"; import { JwtOptionsInterface } from "../interfaces/jwt-options.interface"; import { PlaceholderDto } from "../dtos/placeholder.dto"; export class BaseController { public methods: number[] = []; public jwtConfig: JwtOptionsInterface; public requiresAuth = false; constructor(public repository: any) {} sign(data): Promise { return jwt.sign({ data }, this.jwtConfig.secret, { expiresIn: this.jwtConfig.expiresIn }); } verify(authorization): Promise { return jwt.verify( (authorization || "").substring(7), this.jwtConfig.secret ); } @All() async all( @Headers("authorization") authorization, @Req() req: Request, @Res() res: Response, @Next() next: Function ): Promise { if (this.methods.includes(RequestMethod[req.method])) { if (this.requiresAuth) { try { await this.verify(authorization); next(); } catch (e) { throw new UnauthorizedException(); } } else { next(); } } else { res.status(HttpStatus.NOT_FOUND).json(); } } @Get() async findAll(@Query() query: QueryDto, @Res() res: Response): Promise { res.json({ data: { total: await this.repository.count(query), items: await this.repository.findAll(query) } }); } @Get(":id") async findByPk(@Param("id") id: string, @Res() res: Response): Promise { const ret = await this.repository.findByPk(id); if (ret) { res.json({ data: ret }); } else { res.status(HttpStatus.NOT_FOUND).json(); } } @Post() async create( @Body() body: PlaceholderDto, @Res() res: Response ): Promise { res.json({ data: await this.repository.create(body) }); } @Put(":id") async update( @Param("id") id: string, @Body() body: PlaceholderDto, @Res() res: Response ): Promise { const ret = await this.repository.update(body, { where: { id } }); if (ret[0]) { res.json(); } else { res.status(HttpStatus.NOT_FOUND).json(); } } @Delete(":id") async destroy(@Param("id") id: string, @Res() res: Response): Promise { const ret = await this.repository.destroy({ where: { id } }); if (ret) { res.json(); } else { res.status(HttpStatus.NOT_FOUND).json(); } } }