UNPKG

getting-better-prueba-common-library

Version:
56 lines (47 loc) 1.63 kB
import { Request, Response, NextFunction, Errback } from "express"; import winston, { format, transports } from "winston" import { ErrorDto } from "./types/error.dto"; import { BaseResponseDto } from "./types/baseResponse.dto"; export const logger = winston.createLogger(); if (process.env.NODE_ENV !== 'production') { logger.add(new transports.Console({ format: format.combine( format.colorize(), format.timestamp(), format.printf(info => `${info.timestamp} ${info.level}: ${info.message}`) ), })); } const errorHandler = (err: ErrorDto, req: Request, res: Response, next: NextFunction) : void => { logger.error(err.message) res.status(500).json({ error: { code: 500, message: err.message, }}); next(); } const routeNotFoundHandler = (req: Request, res: Response, next: NextFunction) : void => { res.status(404).json({ error: { code: 404, message: "Route not found.", } }) } const isUserAuthenticated = (req: Request, res: Response, next: NextFunction) : void => { if (req.session.username) { next(); } else { logger.warn(`${req.url} : Hubo un intento de acceso no autorizado.`) const notAuthenticatedResponse: BaseResponseDto = { "error": { "code": 403, "message": "Debe iniciar sesión para acceder a este recurso." } } res.status(403).send(notAuthenticatedResponse); } } export default { errorHandler, routeNotFoundHandler, isUserAuthenticated }