Request-Promise Middleware Framework
This package provides a framework for intercepting and modifying HTTP requests and responses made using the `request-promise` HTTP client. It enables developers to define middleware functions that can execute custom logic before an HTTP call, modify request options, or process responses. The current stable version is 3.0.6. The release cadence appears to be irregular, driven primarily by dependency updates and security fixes rather than new feature additions. A key differentiator is its explicit handling of `resolveWithFullResponse`, defaulting it to `true` within the middleware pipeline to ensure full response access for all middleware components, diverging slightly from `request-promise`'s default. This framework is specifically designed for `request-promise` and does not support other HTTP clients, serving as a dedicated extensibility layer for that ecosystem.
Common errors
-
TypeError: rpMiddlewareFramework.getMiddlewareEnabledRequestPromise is not a function
cause The `RequestPromiseMiddlewareFramework` constructor or instance was not correctly created or imported, or you're calling the method on a variable that isn't the framework instance.fixEnsure you correctly `require` or `import` the `RequestPromiseMiddlewareFramework` and instantiate it with `new RequestPromiseMiddlewareFramework(...)` before calling `getMiddlewareEnabledRequestPromise()`. -
Error: Cannot find module 'request-promise'
cause The `request-promise` package is a required peer/runtime dependency that must be installed separately.fixInstall `request-promise` using npm: `npm install request-promise`. -
UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: X): Error: ...
cause A promise returned by `request-promise-middleware-framework` (or `request-promise`) was rejected, but the rejection was not caught by a `.catch()` block or `try...catch` in an `async` function.fixAlways add a `.catch()` block to your promise chains (e.g., `rp(...).then(...).catch(err => console.error(err))`) or use `try...catch` with `await` in `async` functions to handle potential errors.
Warnings
- breaking Version 3.0.0 removed the dependency on `bluebird` and now utilizes native Promises by default. If your application relied on `bluebird`'s specific features or custom Promise extensions, you might need to adjust your code or explicitly provide `bluebird` to the framework initialization.
- breaking Version 1.0.0 changed the default behavior for `resolveWithFullResponse` to `true`. While `request-promise` typically defaults this to `false`, this framework forces it to `true` internally for middleware consistency. If your code explicitly expected `resolveWithFullResponse: false` by default and was not setting it, this change would affect the shape of the returned value.
- gotcha The framework's default for `resolveWithFullResponse` is `true` within the middleware pipeline, overriding `request-promise`'s default. While you can set `resolveWithFullResponse: false` on an individual `rp` invocation, the middleware pipeline itself will internally always operate with the full response object for consistency, potentially leading to unexpected behavior if middleware expects only the body.
- breaking Security vulnerabilities are periodically patched (e.g., in v3.0.6, v3.0.5, v3.0.3) often related to underlying dependencies like `eslint-utils` or other core packages. Failing to update to the latest patch versions can expose applications to known CVEs.
Install
-
npm install request-promise-middleware-framework -
yarn add request-promise-middleware-framework -
pnpm add request-promise-middleware-framework
Imports
- RequestPromiseMiddlewareFramework
const RequestPromiseMiddlewareFramework = require('request-promise-middleware-framework');import RequestPromiseMiddlewareFramework from 'request-promise-middleware-framework';
- RequestPromiseMiddlewareFramework (CJS)
const RequestPromiseMiddlewareFramework = require('request-promise-middleware-framework');
Quickstart
import RequestPromiseMiddlewareFramework from 'request-promise-middleware-framework';
import rpBase from 'request-promise';
// Define a simple logging middleware
function loggingMiddleware(options, callback, next) {
console.log(`[Middleware] Requesting: ${options.uri || options.url}`);
const _callback = (err, response, body) => {
if (err) {
console.error(`[Middleware] Error for ${options.uri || options.url}:`, err.message);
} else {
console.log(`[Middleware] Received response for ${options.uri || options.url} with status: ${response ? response.statusCode : 'N/A'}`);
}
callback(err, response, body);
};
next(options, _callback);
}
// Define a short-circuiting middleware example
function shortCircuitMiddleware(options, callback, next) {
if (options.uri === 'http://example.com/short-circuit') {
console.log('[Middleware] Short-circuiting request to http://example.com/short-circuit');
const mockBody = { message: 'Short-circuited by middleware' };
const mockResponse = { statusCode: 200, body: mockBody, headers: { 'content-type': 'application/json' } };
callback(null, mockResponse, mockBody);
} else {
next(options, callback);
}
}
// Initialize the framework with request-promise and our middleware
const rpMiddlewareFramework = new RequestPromiseMiddlewareFramework(
{ rp: rpBase },
[loggingMiddleware, shortCircuitMiddleware]
);
// Get the middleware-enabled request-promise instance
const rp = rpMiddlewareFramework.getMiddlewareEnabledRequestPromise();
// Use the new rp instance
async function makeRequests() {
try {
// Request that goes through the network
const result1 = await rp('http://httpbin.org/get');
console.log('Result 1 (full response body snippet):', result1.slice(0, 100), '...');
// Request that is short-circuited
const result2 = await rp('http://example.com/short-circuit');
console.log('Result 2 (short-circuited):', result2);
} catch (error) {
console.error('An error occurred:', error.message);
}
}
makeRequests();