Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: explicitly check that request.body is a string #1010

Merged
merged 3 commits into from
May 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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");
});
});
Loading