UNPKG

@sentzunhat/zacatl

Version:

A modular, high-performance TypeScript microservice framework for Node.js, featuring layered architecture, dependency injection, and robust validation for building scalable APIs and distributed systems.

82 lines 2.62 kB
import { BadRequestError, BadResourceError, ForbiddenError, InternalServerError, NotFoundError, UnauthorizedError, ValidationError, } from '../../../../../../../error/index.js'; export class AbstractRouteHandler { url; method; schema; constructor(args) { this.url = args.url; this.method = args.method; this.schema = args.schema; } handleError(error) { if (error instanceof NotFoundError) { return { message: error.message, statusCode: 404, }; } if (error instanceof BadRequestError || error instanceof BadResourceError) { return { message: error.message, statusCode: 400, }; } if (error instanceof ValidationError) { return { message: error.message, statusCode: 422, }; } if (error instanceof UnauthorizedError) { return { message: error.message, statusCode: 401, }; } if (error instanceof ForbiddenError) { return { message: error.message, statusCode: 403, }; } if (error instanceof InternalServerError) { return { message: error.message, statusCode: 500, }; } return { message: 'Something went wrong', statusCode: 500, }; } async execute(request, reply) { try { const result = await this.handler(request); if (!reply.sent) { await reply.send(result); } return result; } catch (error) { if (!reply.sent) { const errorResponse = this.handleError(error); const statusCode = typeof errorResponse === 'object' && errorResponse !== null && 'statusCode' in errorResponse ? errorResponse.statusCode || 500 : 500; let body = errorResponse; if (typeof errorResponse === 'object' && errorResponse !== null && 'statusCode' in errorResponse) { const { statusCode: _, ...rest } = errorResponse; body = rest; } await reply.code(statusCode).send(body); } throw error; } } } //# sourceMappingURL=abstract.js.map