Skip to content

Commit

Permalink
fix: explicitly check that request.body is a string (#1010)
Browse files Browse the repository at this point in the history
* fix: reverts conditional change within `getPayload()` that broke compatibility with fastify/middie middleware library

* updates conditional within `getPayload()`
  • Loading branch information
didley authored May 6, 2024
1 parent 4e778f9 commit c9b988d
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 12 deletions.
22 changes: 10 additions & 12 deletions src/middleware/node/get-payload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,18 +12,16 @@ import AggregateError from "aggregate-error";
type IncomingMessage = any;

export function getPayload(request: IncomingMessage): Promise<string> {
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)
Expand Down
15 changes: 15 additions & 0 deletions test/integration/get-payload.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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");
});
});

0 comments on commit c9b988d

Please sign in to comment.