Skip to content

Commit

Permalink
Adds raw body to request after reading in node-http integration (#52)
Browse files Browse the repository at this point in the history
* fixes request read issue
* fixed linting errors
  • Loading branch information
amorey authored Jun 25, 2024
1 parent 715b3e4 commit a1c5f64
Showing 1 changed file with 37 additions and 13 deletions.
50 changes: 37 additions & 13 deletions packages/node-http/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,29 +7,53 @@ import type { ConfigOptions } from '@shared/protect';

export { CsrfError };

interface IncomingMessageWithBody extends IncomingMessage {
body?: any;
}

/**
* Parse request body as string
* @param {IncomingMessage} req - The node http request
* @returns Promise that resolves to the body
*/
function getRequestBody(req: IncomingMessage): Promise<string> {
function getRequestBody(req: IncomingMessageWithBody): Promise<string> {
return new Promise((resolve, reject) => {
let body = '';
const buffer: any[] = [];

req.on('data', (chunk) => {
body += chunk.toString();
});
const onAborted = () => {
reject(new Error('request aborted'));
};

req.on('end', () => {
// reset body
req.push(body);
req.push(null);
const onData = (chunk: any) => {
buffer.push(chunk);
};

// resolve promise
resolve(body);
});
const onEnd = () => {
// add `body` to request for downstream readers
req.body = Buffer.concat(buffer);

req.on('error', (err) => reject(err));
// resolve promise
resolve(req.body.toString());
};

const onErr = (err: Error) => {
reject(err);
};

const onClose = () => {
req.removeListener('data', onData);
req.removeListener('end', onEnd);
req.removeListener('err', onErr);
req.removeListener('aborted', onAborted);
req.removeListener('close', onClose);
};

// attach listeners
req.on('aborted', onAborted);
req.on('data', onData);
req.on('end', onEnd);
req.on('err', onErr);
req.on('close', onClose);
});
}

Expand Down

0 comments on commit a1c5f64

Please sign in to comment.