import { RouteHandlerMethod } from 'fastify'; import { AdderService, AdderServiceImpl, ArgumentOutOfRangeError, InvalidArgumentTypeError, } from '@/modules/adder/adder.service'; import { constants } from 'http2'; export interface AdderController { addNumbers: RouteHandlerMethod; subtractNumbers: RouteHandlerMethod; } export class AdderControllerImpl implements AdderController { constructor( private readonly adderService: AdderService = new AdderServiceImpl(), ) { // noop } readonly addNumbers: RouteHandlerMethod = async (request, reply) => { const { a, b } = request.body as { a: number; b: number }; try { const response = this.adderService.addNumbers({ a, b }); reply.send(response); } catch (errorRaw) { if (errorRaw instanceof InvalidArgumentTypeError) { request.log.info(errorRaw); reply.status(constants.HTTP_STATUS_BAD_REQUEST).send(errorRaw.message); return; } if (errorRaw instanceof ArgumentOutOfRangeError) { reply.status(constants.HTTP_STATUS_BAD_REQUEST).send(errorRaw.message); return; } const error = errorRaw as Error; reply.status(constants.HTTP_STATUS_INTERNAL_SERVER_ERROR).send(error.message); } } readonly subtractNumbers: RouteHandlerMethod = async (request, reply) => { const { a, b } = request.body as { a: number; b: number }; try { const response = this.adderService.addNumbers({ a, b: -b }); reply.send(response); } catch (errorRaw) { if (errorRaw instanceof InvalidArgumentTypeError) { reply.status(constants.HTTP_STATUS_BAD_REQUEST).send(errorRaw.message); return; } if (errorRaw instanceof ArgumentOutOfRangeError) { reply.status(constants.HTTP_STATUS_BAD_REQUEST).send(errorRaw.message); return; } const error = errorRaw as Error; reply.status(constants.HTTP_STATUS_INTERNAL_SERVER_ERROR).send(error.message); } } }