Skip to content

Commit 4a9afd7

Browse files
authored
feat(middlware): allow string payloads (#799)
* feat(middleware): allow payload to be a string * fix(middleware): don't parse the payload string into JSON If we don't have `request.body`, don't parse the string payload into JSON, to avoid issues like #775 * style: prettier * feat(middleware): deprecate passing a payload as JSON in `request.body` * fix(middleware): test if string can be parsed as JSON
1 parent 0107330 commit 4a9afd7

File tree

1 file changed

+14
-3
lines changed

1 file changed

+14
-3
lines changed

src/middleware/node/get-payload.ts

+14-3
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,20 @@ import AggregateError from "aggregate-error";
1212
// }
1313
type IncomingMessage = any;
1414

15-
export function getPayload(request: IncomingMessage): Promise<WebhookEvent> {
15+
export function getPayload(
16+
request: IncomingMessage
17+
): Promise<WebhookEvent | string> {
1618
// If request.body already exists we can stop here
1719
// See https://github.com/octokit/webhooks.js/pull/23
1820

19-
if (request.body) return Promise.resolve(request.body as WebhookEvent);
21+
if (request.body) {
22+
if (typeof request.body !== "string") {
23+
console.error(
24+
"[@octokit/webhooks] Passing the payload as a JSON object in `request.body` is deprecated and will be removed in a future release of `@octokit/webhooks`, please pass it as a a `string` instead."
25+
);
26+
}
27+
return Promise.resolve(request.body as WebhookEvent | string);
28+
}
2029

2130
return new Promise((resolve, reject) => {
2231
let data = "";
@@ -28,7 +37,9 @@ export function getPayload(request: IncomingMessage): Promise<WebhookEvent> {
2837
request.on("data", (chunk: string) => (data += chunk));
2938
request.on("end", () => {
3039
try {
31-
resolve(JSON.parse(data));
40+
// Call JSON.parse() only to check if the payload is valid JSON
41+
JSON.parse(data);
42+
resolve(data);
3243
} catch (error: any) {
3344
error.message = "Invalid JSON";
3445
error.status = 400;

0 commit comments

Comments
 (0)