Skip to content

Commit

Permalink
feat(middlware): allow string payloads (#799)
Browse files Browse the repository at this point in the history
* 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
  • Loading branch information
wolfy1339 committed Jan 12, 2023
1 parent 0107330 commit 4a9afd7
Showing 1 changed file with 14 additions and 3 deletions.
17 changes: 14 additions & 3 deletions src/middleware/node/get-payload.ts
Expand Up @@ -12,11 +12,20 @@ import AggregateError from "aggregate-error";
// }
type IncomingMessage = any;

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

if (request.body) return Promise.resolve(request.body as WebhookEvent);
if (request.body) {
if (typeof request.body !== "string") {
console.error(
"[@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."
);
}
return Promise.resolve(request.body as WebhookEvent | string);
}

return new Promise((resolve, reject) => {
let data = "";
Expand All @@ -28,7 +37,9 @@ export function getPayload(request: IncomingMessage): Promise<WebhookEvent> {
request.on("data", (chunk: string) => (data += chunk));
request.on("end", () => {
try {
resolve(JSON.parse(data));
// Call JSON.parse() only to check if the payload is valid JSON
JSON.parse(data);
resolve(data);
} catch (error: any) {
error.message = "Invalid JSON";
error.status = 400;
Expand Down

0 comments on commit 4a9afd7

Please sign in to comment.