Skip to content

Commit

Permalink
fix(firebase-handler): issue when firebase send body as object instea…
Browse files Browse the repository at this point in the history
…d buffer

fix #40
  • Loading branch information
H4ad committed Aug 5, 2022
1 parent 8e5588f commit a20ca99
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 1 deletion.
15 changes: 14 additions & 1 deletion src/handlers/firebase/http-firebase.handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import { IncomingMessage, ServerResponse } from 'http';
import { https } from 'firebase-functions';
import { FrameworkContract, HandlerContract } from '../../contracts';
import { ServerlessRequest } from '../../network';

//#endregion

Expand All @@ -29,7 +30,19 @@ export class HttpFirebaseHandler<TApp>
): (req: IncomingMessage, res: ServerResponse) => void | Promise<void> {
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);
},
);
}
Expand Down
44 changes: 44 additions & 0 deletions test/handlers/http-firebase.handler.spec.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
import {
AdapterContract,
FrameworkContract,
createDefaultLogger,
} from '../../lib';
import {
ServerlessRequest,
ServerlessResponse,
Expand Down Expand Up @@ -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<unknown> = {
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,
);
}
});
});

0 comments on commit a20ca99

Please sign in to comment.