From b5e356d724ae2cb446da2b226585d1961e34e5dc Mon Sep 17 00:00:00 2001 From: yldrmzffr Date: Thu, 2 Nov 2023 08:38:39 +0300 Subject: [PATCH] fix(async error): fixed Async Exception handler and added async tests --- lib/index.ts | 11 ++++++----- package.json | 2 +- test/methods.test.ts | 42 +++++++++++++++++++++++++++++++++++++++++- 3 files changed, 48 insertions(+), 7 deletions(-) diff --git a/lib/index.ts b/lib/index.ts index 21d63cb..fac48ad 100644 --- a/lib/index.ts +++ b/lib/index.ts @@ -38,10 +38,6 @@ export class MuzuServer { statusCode: number, body: Object ): Promise { - if (body instanceof Promise) { - body = await body; - } - res.writeHead(statusCode, {'Content-Type': 'application/json'}); res.end(JSON.stringify(body)); console.log('📤 Response', {statusCode, body}); @@ -72,7 +68,12 @@ export class MuzuServer { throw new BadRequestException('Error parsing body', err.details); } - const result = route.handler(req, res); + let result: Object = route.handler(req, res); + + if (result instanceof Promise) { + result = await result; + } + const statusCode = res.statusCode || 200; return this.sendResponse(res, statusCode, result); } catch (error) { diff --git a/package.json b/package.json index cbf2bc2..51a7571 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "muzu", - "version": "0.0.5", + "version": "0.0.6", "description": "", "main": "build/lib/index.js", "types": "build/lib/index.d.ts", diff --git a/test/methods.test.ts b/test/methods.test.ts index def2fb9..5b04873 100644 --- a/test/methods.test.ts +++ b/test/methods.test.ts @@ -1,4 +1,4 @@ -import {MuzuServer, Request} from '../lib'; +import {MuzuServer, Request, HttpException} from '../lib'; import * as request from 'supertest'; const muzuServer = new MuzuServer(); @@ -30,6 +30,26 @@ class TestController { helloPatch() { return {message: 'Patch Method Called'}; } + + asyncReturn() { + return new Promise(resolve => { + setTimeout(() => { + resolve({message: 'Async Method Called'}); + }, 300); + }); + } + + @Post('/async-hello') + async asyncHello() { + const result = await this.asyncReturn(); + console.log('result', result); + return result; + } + + @Post('/async-error') + async asyncError() { + throw new HttpException(400, 'Async Error'); + } } const port = 3000; @@ -93,6 +113,26 @@ describe('MuzuServer', () => { status: 400, }); }); + + it('should return 200 on POST /api/async-hello', async () => { + const res = await request(muzuServer.server) + .post('/api/async-hello') + .send({name: 'Muzu'}); + expect(res.status).toEqual(200); + expect(res.body).toEqual({message: 'Async Method Called'}); + }); + + it('should return 400 on POST /api/async-error', async () => { + const res = await request(muzuServer.server) + .post('/api/async-error') + .send({name: 'Muzu'}); + expect(res.status).toEqual(400); + expect(res.body).toEqual({ + kind: 'MuzuException', + message: 'Async Error', + status: 400, + }); + }); }); muzuServer.stop(() => {