Skip to content

Commit c9b988d

Browse files
authored
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()`
1 parent 4e778f9 commit c9b988d

File tree

2 files changed

+25
-12
lines changed

2 files changed

+25
-12
lines changed

src/middleware/node/get-payload.ts

+10-12
Original file line numberDiff line numberDiff line change
@@ -12,18 +12,16 @@ import AggregateError from "aggregate-error";
1212
type IncomingMessage = any;
1313

1414
export function getPayload(request: IncomingMessage): Promise<string> {
15-
if ("body" in request) {
16-
if (
17-
typeof request.body === "object" &&
18-
"rawBody" in request &&
19-
request.rawBody instanceof Buffer
20-
) {
21-
// The body is already an Object and rawBody is a Buffer (e.g. GCF)
22-
return Promise.resolve(request.rawBody.toString("utf8"));
23-
} else {
24-
// The body is a String (e.g. Lambda)
25-
return Promise.resolve(request.body);
26-
}
15+
if (
16+
typeof request.body === "object" &&
17+
"rawBody" in request &&
18+
request.rawBody instanceof Buffer
19+
) {
20+
// The body is already an Object and rawBody is a Buffer (e.g. GCF)
21+
return Promise.resolve(request.rawBody.toString("utf8"));
22+
} else if (typeof request.body === "string") {
23+
// The body is a String (e.g. Lambda)
24+
return Promise.resolve(request.body);
2725
}
2826

2927
// We need to load the payload from the request (normal case of Node.js server)

test/integration/get-payload.test.ts

+15
Original file line numberDiff line numberDiff line change
@@ -74,4 +74,19 @@ describe("getPayload", () => {
7474

7575
expect(await promise).toEqual("foo");
7676
});
77+
78+
it("resolves with a string if the body key of the request is defined but value is undefined", async () => {
79+
const request = new EventEmitter();
80+
// @ts-ignore body is not part of EventEmitter, which we are using
81+
// to mock the request object
82+
request.body = undefined;
83+
84+
const promise = getPayload(request);
85+
86+
// we emit data, to ensure that the body attribute is preferred
87+
request.emit("data", "bar");
88+
request.emit("end");
89+
90+
expect(await promise).toEqual("bar");
91+
});
7792
});

0 commit comments

Comments
 (0)