From a20ca99e40f3615eec03b8ec959125a4cdad7c29 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vin=C3=ADcius=20Louren=C3=A7o?= Date: Fri, 5 Aug 2022 19:38:04 -0300 Subject: [PATCH] fix(firebase-handler): issue when firebase send body as object instead buffer fix #40 --- .../firebase/http-firebase.handler.ts | 15 ++++++- test/handlers/http-firebase.handler.spec.ts | 44 +++++++++++++++++++ 2 files changed, 58 insertions(+), 1 deletion(-) diff --git a/src/handlers/firebase/http-firebase.handler.ts b/src/handlers/firebase/http-firebase.handler.ts index a8cdfead..8b44257f 100644 --- a/src/handlers/firebase/http-firebase.handler.ts +++ b/src/handlers/firebase/http-firebase.handler.ts @@ -3,6 +3,7 @@ import { IncomingMessage, ServerResponse } from 'http'; import { https } from 'firebase-functions'; import { FrameworkContract, HandlerContract } from '../../contracts'; +import { ServerlessRequest } from '../../network'; //#endregion @@ -29,7 +30,19 @@ export class HttpFirebaseHandler ): (req: IncomingMessage, res: ServerResponse) => void | Promise { return https.onRequest( (request: IncomingMessage, response: ServerResponse) => { - return framework.sendRequest(app, request, response); + const serverlessRequest = request as ServerlessRequest; + + if ( + serverlessRequest.body && + typeof serverlessRequest.body === 'object' + ) { + serverlessRequest.body = Buffer.from( + JSON.stringify(serverlessRequest.body), + 'utf-8', + ); + } + + return framework.sendRequest(app, serverlessRequest, response); }, ); } diff --git a/test/handlers/http-firebase.handler.spec.ts b/test/handlers/http-firebase.handler.spec.ts index cc2b98ad..04a516f9 100644 --- a/test/handlers/http-firebase.handler.spec.ts +++ b/test/handlers/http-firebase.handler.spec.ts @@ -1,3 +1,8 @@ +import { + AdapterContract, + FrameworkContract, + createDefaultLogger, +} from '../../lib'; import { ServerlessRequest, ServerlessResponse, @@ -59,4 +64,43 @@ describe(HttpFirebaseHandler.name, () => { JSON.stringify(responseBody), ); }); + + it('should handle weird body types', () => { + const handlerFactory = new HttpFirebaseHandler(); + + const method = 'POST'; + const url = '/users/batata'; + const headers = { 'Content-Type': 'application/json' }; + const remoteAddress = '168.16.0.1'; + const options = [{ potato: true }, [{ test: true }]]; + + for (const option of options) { + const request = new ServerlessRequest({ + method, + url, + headers, + remoteAddress, + body: option as any, + }); + + const response = new ServerlessResponse({ + method, + }); + + const framework: FrameworkContract = { + sendRequest: jest.fn(), + }; + + const handler = handlerFactory.getHandler(null, framework); + + handler(request, response); + + // eslint-disable-next-line @typescript-eslint/unbound-method + expect(framework.sendRequest).toHaveBeenCalledWith( + null, + expect.objectContaining({ body: Buffer.from(JSON.stringify(option)) }), + response, + ); + } + }); });