From c9b988d875c0493efb0662cce40350c86675420e Mon Sep 17 00:00:00 2001 From: Dylan Lamont <38599829+didley@users.noreply.github.com> Date: Mon, 6 May 2024 13:02:32 +1000 Subject: [PATCH] fix: explicitly check that `request.body` is a string (#1010) * fix: reverts conditional change within `getPayload()` that broke compatibility with fastify/middie middleware library * updates conditional within `getPayload()` --- src/middleware/node/get-payload.ts | 22 ++++++++++------------ test/integration/get-payload.test.ts | 15 +++++++++++++++ 2 files changed, 25 insertions(+), 12 deletions(-) diff --git a/src/middleware/node/get-payload.ts b/src/middleware/node/get-payload.ts index cb873665..cead47c0 100644 --- a/src/middleware/node/get-payload.ts +++ b/src/middleware/node/get-payload.ts @@ -12,18 +12,16 @@ import AggregateError from "aggregate-error"; type IncomingMessage = any; export function getPayload(request: IncomingMessage): Promise { - if ("body" in request) { - if ( - typeof request.body === "object" && - "rawBody" in request && - request.rawBody instanceof Buffer - ) { - // The body is already an Object and rawBody is a Buffer (e.g. GCF) - return Promise.resolve(request.rawBody.toString("utf8")); - } else { - // The body is a String (e.g. Lambda) - return Promise.resolve(request.body); - } + if ( + typeof request.body === "object" && + "rawBody" in request && + request.rawBody instanceof Buffer + ) { + // The body is already an Object and rawBody is a Buffer (e.g. GCF) + return Promise.resolve(request.rawBody.toString("utf8")); + } else if (typeof request.body === "string") { + // The body is a String (e.g. Lambda) + return Promise.resolve(request.body); } // We need to load the payload from the request (normal case of Node.js server) diff --git a/test/integration/get-payload.test.ts b/test/integration/get-payload.test.ts index 507f4a93..c28aa7e9 100644 --- a/test/integration/get-payload.test.ts +++ b/test/integration/get-payload.test.ts @@ -74,4 +74,19 @@ describe("getPayload", () => { expect(await promise).toEqual("foo"); }); + + it("resolves with a string if the body key of the request is defined but value is undefined", async () => { + const request = new EventEmitter(); + // @ts-ignore body is not part of EventEmitter, which we are using + // to mock the request object + request.body = undefined; + + const promise = getPayload(request); + + // we emit data, to ensure that the body attribute is preferred + request.emit("data", "bar"); + request.emit("end"); + + expect(await promise).toEqual("bar"); + }); });