UNPKG

@sap-cloud-sdk/resilience

Version:

SAP Cloud SDK for JavaScript resilience

54 lines 2.13 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.timeout = timeout; const util_1 = require("@sap-cloud-sdk/util"); const defaultTimeout = 10000; const logger = (0, util_1.createLogger)({ package: 'resilience', messageContext: 'timeout' }); /** * Helper method to build a timeout middleware. * @param timeoutValue - Timeout in milliseconds. Default value is 10000. * @returns The middleware adding a timeout to the function. */ function timeout(timeoutValue = defaultTimeout) { if (timeoutValue <= 0) { throw new Error('Timeout must be greater than 0.'); } if (timeoutValue < 10) { logger.warn(`The timeout of ${timeoutValue} ms is too low. Make sure this is not intentional.`); } return function (options) { const message = `Request to URL: ${options.context.uri} ran into a timeout after ${timeoutValue}ms.`; return arg => wrapInTimeout(options.fn(arg), timeoutValue, message); }; } /** * Creates a promise for a timeout race. * @internal * @param timeoutValue - Value for the timeout in milliseconds. * message: string - Error message thrown when timeout is exceeded. * @returns A promise which times out after the given time and the node timeout instance to clear the timeout if not needed anymore. */ function getTimeoutPromise(timeoutValue, message) { let timeoutNode; const promise = new Promise((resolve, reject) => { timeoutNode = setTimeout(() => reject(new Error(message)), timeoutValue); }); return [promise, timeoutNode]; } /** * @param promise - Promise * @param timeoutValue - Value for the timeout in milliseconds. * @internal */ async function wrapInTimeout(promise, timeoutValue, message) { const [timeoutPromise, timeoutInstance] = getTimeoutPromise(timeoutValue, message); // Clear the timeout if the original promise is resolve or reject to avoid open handlers. const withClearTimeout = promise.finally(() => { clearTimeout(timeoutInstance); }); return Promise.race([withClearTimeout, timeoutPromise]); } //# sourceMappingURL=timeout.js.map