My application uses NodeJS https request (https://nodejs.org/api/https.html) to make outgoing calls.
I need to intercept it and first fetch the request body. Once the request is fetched, I'm preparing a modified request and want the modified request to be executed instead of the original intercepted request.
The problem is that, it makes two calls. One with the modified request and one with the original request.
This is what I have so far.
Interceptor -
import { Helper } from '@internal/helper';const https = require('https');export class Interceptor { private originalHttpRequest: any; private readonly helper: Helper; constructor() { this.helper = new Helper(); } startInterceptor() { this.originalHttpRequest = https.request; https.request = this.intercept.bind(this); } intercept(options: any, callback: any) { try { if (options.method === 'POST') { const originalRequestBodyChunks: Buffer[] = []; let originalRequest = this.originalHttpRequest(options, callback); originalRequest.write = function write(data: any, encoding: any) { let requestData = data; if (typeof requestData === 'string') { requestData = Buffer.from(requestData, encoding); } originalRequestBodyChunks.push(requestData); }; originalRequest.on('finish', () => { options.body = Buffer.concat(originalRequestBodyChunks).toString(); const modifiedRequest = this.interceptInternal(options, callback); originalRequest = modifiedRequest; return originalRequest; }); return originalRequest; } else { return this.interceptInternal(options, callback); } } catch (e) { // eslint-disable-next-line no-console console.log('Error intercepting the http request : ', e); return this.originalHttpRequest(options, callback); } } private interceptInternal(options: any, callback: any) { const newOptions = this.helper.getInterceptedRequest('https', options, ); // eslint-disable-next-line no-console const req = this.originalHttpRequest(newOptions, callback); req.write(newOptions.body); return req; }}
Start the interceptor in the application -
import { Interceptor } from '@internal/interceptor';const interceptor = new Interceptor();interceptor.startInterceptor();