straw-hat-team / nodejs-monorepo

Monorepo for the open-source packages
MIT License
7 stars 2 forks source link

Add Retry middleware #4

Open yordis opened 2 years ago

yordis commented 2 years ago

Problem Statement

Reading this article, https://blog.bearer.sh/add-retry-to-api-calls-javascript-node/ Maybe would be a good idea to add a retry middleware

Solution Brainstorm

function fetchRetry(url, options = {}, retries = 3, backoff = 300) {
  /* 1 */
  const retryCodes = [408, 500, 502, 503, 504, 522, 524]
  return fetch(url, options)
    .then(res => {
      if (res.ok) return res.json()

      if (retries > 0 && retryCodes.includes(res.status)) {
        setTimeout(() => {
          /* 2 */
          return fetchRetry(url, options, retries - 1, backoff * 2) /* 3 */
        }, backoff) /* 2 */
      } else {
        throw new Error(res)
      }
    })
    .catch(console.error)
}
stale[bot] commented 2 years ago

This issue has been automatically marked as "Stale: Discard". If this issue still relevant, please leave any comment (for example, "bump"), and we'll keep it open. We are sorry that we haven't been able to prioritize it yet. If you have any new additional information, please include it with your comment.