{"name":"requestretry","description":"request-retry wrap nodejs request to retry http(s) requests in case of error","version":"8.0.0","author":{"name":"Francois-Guillaume Ribreau","email":"npm@fgribreau.com","url":"http://fgribreau.com"},"contributors":[{"name":"juliendangers","email":"dev@juliencrestin.com"},{"name":"Osbert Orr","email":"dev@osbert.net"}],"repository":{"url":"git+https://github.com/FGRibreau/node-request-retry.git"},"main":"index.js","scripts":{"test":"mocha -t 5000 -R spec $(find test -name '*.test.js')","test-watch":"mocha -t 100000 -R min -w $(find test -name '*.test.js')","test-coverage":"nyc --all --statements=100 --lines=100 --functions=100 --branches=100 --check-coverage --reporter=lcov --reporter=cobertura --report-dir=coverage -- mocha -R spec -t 100000  $(find test -name '*.test.js')","update":"updtr","release-after-pr":"git pull --rebase && npm run test-coverage && npm-release patch","changelog":"conventional-changelog -i CHANGELOG.md -s -r 0","changelog-git":"npm run changelog && git add CHANGELOG.md && git commit -m 'docs(changelog): updated' && git push origin master","postpublish":"npm run --silent changelog-git || true"},"license":"MIT","nyc":{"exclude":["node_modules","dist","coverage","webpack.config.js","test"]},"dependencies":{"extend":"^3.0.2","lodash":"^4.17.15"},"peerDependencies":{"postman-request":"^2.88.1-postman"},"devDependencies":{"bluebird":"^3.5.1","chai":"^4.2.0","conventional-changelog":"^7.1.1","conventional-changelog-cli":"^2.0.11","kew":"~0.7.0","mocha":"^11.7.4","npm-release":"^0.0.2","nyc":"^15.1.0","postman-request":"^2.88.1-postman","q":"^1.5.1","rsvp":"^4.8.4","sinon":"^6.1.4"},"_id":"requestretry@8.0.0","gitHead":"0518cd89eb181e80f2bc55e4f75eb829a6fd8554","bugs":{"url":"https://github.com/FGRibreau/node-request-retry/issues"},"homepage":"https://github.com/FGRibreau/node-request-retry#readme","_nodeVersion":"22.14.0","_npmVersion":"10.1.0","dist":{"integrity":"sha512-/79rOV0pEVWVBRk9DfNsEopgnD2mQrJIrFtFBliRWOs7IEeH0IWIdoEEQYg82M4O86mtMxQDKllh3d+YRpBFxA==","shasum":"55b6ddb33446b3432ef46dc7404994fd9840319d","tarball":"http://registry-npm.ywwl.com/requestretry/download/requestretry-8.0.0.tgz","fileCount":12,"unpackedSize":56474,"signatures":[{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEUCID0qtb2lmRPwV7L1W9qSAhaqsORI1ZEc59ZTa7nE0Xz5AiEAoFxY3gQ+X30UZrTpF6SdZ32qHc2TY6DTfOrLOnmYPxI="}],"size":15295,"noattachment":false,"key":"/requestretry/-/requestretry-8.0.0.tgz"},"_npmUser":{"name":"fgribreau","email":"npm@fgribreau.com"},"directories":{},"maintainers":[{"name":"fgribreau","email":"npm@fgribreau.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/requestretry_8.0.0_1761657323900_0.27467590467233904"},"_hasShrinkwrap":false,"readme":"<div align=\"center\">\n  <br><p><strong>request-retry</strong> - HTTP(s) request retry on recoverable errors.</p>\n</div>\n\n------------------------------------------------\n\n[![NPM version](https://img.shields.io/npm/v/requestretry.svg)](http://badge.fury.io/js/requestretry) [![Downloads](http://img.shields.io/npm/dm/requestretry.svg)](https://www.npmjs.com/package/requestretry)\n\n[![Get help on Codementor](https://cdn.codementor.io/badges/get_help_github.svg)](https://www.codementor.io/francois-guillaume-ribreau?utm_source=github&utm_medium=button&utm_term=francois-guillaume-ribreau&utm_campaign=github)  [![available-for-advisory](https://img.shields.io/badge/available%20for%20consulting%20advisory-yes-ff69b4.svg?)](http://bit.ly/2c7uFJq) ![extra](https://img.shields.io/badge/actively%20maintained-yes-ff69b4.svg) [![Slack](https://img.shields.io/badge/Slack-Join%20our%20tech%20community-17202A?logo=slack)](https://join.slack.com/t/fgribreau/shared_invite/zt-edpjwt2t-Zh39mDUMNQ0QOr9qOj~jrg)\n\nWhen the connection fails with one of `ECONNRESET`, `ENOTFOUND`, `ESOCKETTIMEDOUT`, `ETIMEDOUT`, `ECONNREFUSED`, `EHOSTUNREACH`, `EPIPE`, `EAI_AGAIN` or when an HTTP 5xx or 429 error occurrs, the request will automatically be re-attempted as these are often recoverable errors and will go away on retry.\n\n\n> ## ❤️ Shameless plug\n> - Need to implement Webhooks inside your SaaS? [Try Hook0, an open-source self-hostable webhook micro-service](https://www.hook0.com/)\n> - [**Charts, simple as a URL**. No more server-side rendering pain, 1 url = 1 chart](https://image-charts.com)\n> - [Managed **Keycloak IAM** ? Try Cloud-IAM](https://www.cloud-iam.com/)\n> - [Automate your second brain on RoamResearch with Zapier](https://roam-bot.com/)\n\n## Installation\n\nInstall with [npm](https://npmjs.org/package/requestretry).\n\n    npm install --save requestretry\n\n## Usage\n\nRequest-retry is a drop-in replacement for [request](https://github.com/mikeal/request) but adds three new options `maxAttempts`, `retryDelay` and `retryStrategy`. It also adds one property to the response (or the error object, upon a network error), `attempts`. It supports callbacks or promises.\n\n### With callbacks\n\n```javascript\nvar request = require('requestretry');\n\nrequest({\n  url: 'https://api.domain.com/v1/a/b',\n  json: true,\n\n  // The below parameters are specific to request-retry\n  maxAttempts: 5,   // (default) try 5 times\n  retryDelay: 5000,  // (default) wait for 5s before trying again\n  retryStrategy: request.RetryStrategies.HTTPOrNetworkError // (default) retry on 5xx or network errors\n}, function(err, response, body){\n  // this callback will only be called when the request succeeded or after maxAttempts or on error\n  if (response) {\n    console.log('The number of request attempts: ' + response.attempts);\n  }\n});\n```\n\n### With promises\n\nWhen you're using promises, you can pass the two following options:\n- `fullResponse` _(default true)_ - To resolve the promise with the full response or just the body\n- `promiseFactory` _(default whenjs)_ - A function to allow the usage of a different promise implementation library\n\n```javascript\nrequest({\n  url: 'https://api.domain.com/v1/a/b',\n  json: true,\n\n  fullResponse: true // (default) To resolve the promise with the full response or just the body\n})\n.then(function (response) {\n  // response = The full response object or just the body\n})\n.catch(function(error) {\n  // error = Any occurred error\n})\n```\n\n**Using `promiseFactory` option to use a different promise implementation library**\n\n```javascript\n// See the tests for different libraries usage examples\n\n/**\n * @param  {Function} resolver The promise resolver function\n * @return {Object} The promise instance\n */\nfunction customPromiseFactory(resolver) {\n  // With when.js\n  return require('when').promise(resolver);\n\n  // With RSVP.js\n  var Promise = require('rsvp').Promise;\n\n  return new Promise(resolver);\n}\n\nrequest({\n  url: 'https://api.domain.com/v1/a/b',\n  json: true,\n\n  // Custom promise factory function\n  promiseFactory: customPromiseFactory\n})\n.then(function (response) {\n  // response = The full response object or just the body\n})\n.catch(function(error) {\n  // error = Any occurred error\n})\n```\n\n## How to define your own retry strategy\n\nA retry strategy let you specify when request-retry should retry a request\n\n```javascript\n/**\n * @param  {Null | Object} err\n * @param  {Object} response\n * @param  {Object} body\n * @param  {Object} options copy \n * @return {Boolean} true if the request should be retried\n */\nfunction myRetryStrategy(err, response, body, options){\n  // retry the request if we had an error or if the response was a 'Bad Gateway'\n  return !!err || response.statusCode === 502;\n}\n\n/**\n * @param  {Null | Object} err\n * @param  {Object} response\n * @param  {Object} body\n * @param  {Object} options copy \n * @return {Object} mustRetry: {Boolean} true if the request should be retried\n *                  options: {Object} new options for request\n */\nfunction myRetryStrategy(err, response, body, options){\n  options.url = 'new url'; //you can overwrite some attributes or create new object \n  return {\n    mustRetry: !!err || response.statusCode === 502,\n    options: options, //then it should be passed back, it will be used for new requests\n  }\n}\n\n/**\n * With an asynchronous retry strategy\n * @param  {Null | Object} err\n * @param  {Object} response\n * @param  {Object} body\n * @param  {Object} options copy \n * @return {Object} mustRetry: {Boolean} true if the request should be retried\n *                  options: {Object} new options for request\n */\nasync function myRetryStrategy(err, response, body, options){\n  let token = await getNewApiAuthToken();\n  options.headers = {'Authorization': `Bearer ${token}`}\n  return {\n    mustRetry: true,\n    options: options, // retry with new auth token\n  }\n}\n\nrequest({\n  url: 'https://api.domain.com/v1/a/b'\n  json:true,\n  retryStrategy: myRetryStrategy\n}, function(err, response, body){\n  // this callback will only be called when the request succeeded or after maxAttempts or on error\n});\n```\n\n## How to define your own delay strategy\n\nA delay strategy let you specify how long request-retry should wait before trying again the request\n\n```javascript\n/**\n * @param  {Null | Object} err\n * @param  {Object} response\n * @param  {Object} body\n * @return {Number} number of milliseconds to wait before trying again the request\n */\nfunction myDelayStrategy(err, response, body){\n  // set delay of retry to a random number between 500 and 3500 ms\n  return Math.floor(Math.random() * (3500 - 500 + 1) + 500);\n}\n\nrequest({\n  url: 'https://api.domain.com/v1/a/b'\n  json:true,\n  delayStrategy: myDelayStrategy // delayStrategy is called 1 less times than the maxAttempts set\n}, function(err, response, body){\n  // this callback will only be called when the request succeeded or after maxAttempts or on error\n});\n```\n\nHere is how to implement an exponential backoff strategy:\n\n```javascript\n/**\n * @param   {Number} attempts The number of times that the request has been attempted.\n * @return  {Number} number of milliseconds to wait before retrying again the request.\n */\nfunction getExponentialBackoff(attempts) {\n  return (Math.pow(2, attempts) * 100) + Math.floor(Math.random() * 50);\n}\n\nfunction constructExponentialBackoffStrategy() {\n  let attempts = 0;\n  return () => {\n    attempts += 1;\n    return getExponentialBackoff(attempts);\n  };\n}\n\nrequest({\n  url: 'https://api.domain.com/v1/a/b'\n  json:true,\n  delayStrategy: constructExponentialBackoffStrategy() // need to invoke the function to return the closure.\n}, function(err, response, body){\n  // this callback will only be called when the request succeeded or after maxAttempts or on error\n});\n```\n\n## How to access the underlying request library\n\nYou can access to the underlying `request` library thanks to `request.Request`:\n\n```javascript\nconst request = require('requestretry');\nconsole.log(request.Request); // original request library\n```\n\nThus, if needed, it's possible to monkey-patch or extend the underlying Request library:\n\n```javascript\nrequest.Request = class extends request.Request {\n  constructor(url, options, f, retryConfig) {\n    super(url, options, f, retryConfig);\n    // this constructor will be called for every requestretry call,\n    // and give you global logging\n    console.log('Request', url, options, f, retryConfig);\n  }\n}\n```\n\n\n## Modifying `request` options\n\nYou can use the `defaults` method to provide default options like so:\n\n```javascript\nvar request = require('requestretry').defaults({ json: true, retryStrategy: myRetryStrategy });\n```\n\n## API surface\n\nAs with `request`, several helpers are provided for various HTTP methods and usage:\n\n* `request(options [, callback])`.\n* `request(url [, callback])` - same as `request(options [, callback])`.\n* `request(url, options [, callback])` - same as `request(options [, callback])`.\n* `request.get(url [, callback])` - same as `request(options [, callback])`, defaults `options.method` to `GET`.\n* `request.get(url, options  [, callback])` - same as `request(options [, callback])`, defaults `options.method` to `GET`.\n* `request.head(url)` - same as `request(options [, callback])`, defaults `options.method` to `HEAD`.\n* `request.post(url)` - same as `request(options [, callback])`, defaults `options.method` to `POST`.\n* `request.put(url)` - same as `request(options [, callback])`, defaults `options.method` to `PUT`.\n* `request.patch(url)` - same as `request(options [, callback])`, defaults `options.method` to `PATCH`.\n* `request.del(url)` - same as `request(options [, callback])`, defaults `options.method` to `DELETE`.\n* `request.delete(url)` - same as `request(options [, callback])`, defaults `options.method` to `DELETE`.\n\n## [Changelog](CHANGELOG.md)\n\n## You want to support my work?\n\nI maintain this project in my free time, if it helped you, well, I would be grateful to buy a beer thanks to your [paypal](https://paypal.me/fgribreau) or [Bitcoins](https://www.coinbase.com/fgribreau), donation!\n\n[Francois-Guillaume Ribreau](http://fgribreau.com) (npm@fgribreau.com)\n","publish_time":1761657324086,"_cnpm_publish_time":1761657324086,"dist-tags":{"latest":"8.0.0"}}