Giter Club home page Giter Club logo

wretch-middlewares's Introduction

wretch-logo

Wretch middlewares

homepage-badge npm-badge license-badge

A collection of middlewares for the Wretch library.

Deprecation Notice

โš ๏ธ This repository is now deprecated, middlewares have been integrated into the main wretch package starting from wretch v2.0.0

Installation

Prerequisite: install Wretch

Npm

npm i wretch-middlewares

Cdn

<!-- Global variable name : window.wretchMiddlewares -->
<script src="https://unpkg.com/wretch-middlewares"></script>

Middlewares

Dedupe Retry ย Throttling cache ย Delay

Dedupe

Prevents having multiple identical requests on the fly at the same time.

Options

  • skip : (url, opts) => boolean

If skip returns true, then the dedupe check is skipped.

  • key : (url, opts) => string

Returns a key that is used to identify the request.

  • resolver : (response: Response) => Response

This function is called when resolving the fetch response from duplicate calls. By default it clones the response to allow reading the body from multiple sources.

Usage

import wretch from 'wretch'
import { dedupe } from 'wretch-middlewares'

wretch().middlewares([
    dedupe({
        /* Options - defaults below */
        skip: (url, opts) => opts.skipDedupe || opts.method !== 'GET',
        key: (url, opts) => opts.method + '@' + url,
        resolver: response => response.clone()
    })
])./* ... */

Retry

Retries a request multiple times in case of an error (or until a custom condition is true).

Options

  • delayTimer : milliseconds

The timer between each attempt.

  • delayRamp : (delay, nbOfAttempts) => milliseconds

The custom function that is used to calculate the actual delay based on the the timer & the number of attemps.

  • maxAttempts : number

The maximum number of retries before resolving the promise with the last error. Specifying 0 means infinite retries.

  • until : (fetchResponse, error) => boolean | Promise<boolean>

The request will be retried until that condition is satisfied.

  • onRetry : ({ response, error, url, options }) => { url?, options? } || Promise<{url?, options?}>

Callback that will get executed before retrying the request. If this function returns an object having url and/or options properties, they will override existing values in the retried request. If it returns a Promise, it will be awaited before retrying the request.

  • retryOnNetworkError : boolean

If true, will retry the request if a network error was thrown. Will also provide an 'error' argument to the onRetry and until methods.

  • resolver : (response: Response) => Response

This function is called when resolving the fetch response from duplicate calls. By default it clones the response to allow reading the body from multiple sources.

Usage

import wretch from 'wretch'
import { retry } from 'wretch-middlewares'

wretch().middlewares([
    retry({
        /* Options - defaults below */
        delayTimer: 500,
        delayRamp: (delay, nbOfAttempts) => delay * nbOfAttempts,
        maxAttempts: 10,
        until: (response, error) => response && response.ok,
        onRetry: null,
        retryOnNetworkError: false,
        resolver: response => response.clone()
    })
])./* ... */

// You can also return a Promise, which is useful if you want to inspect the body:
wretch().middlewares([
    retry({
        until: response =>
            response.json().then(body =>
                body.field === 'something'
            )
    })
])

Throttling cache

A throttling cache which stores and serves server responses for a certain amount of time.

Options

  • throttle : milliseconds

The response will be stored for this amount of time before being deleted from the cache.

  • skip : (url, opts) => boolean

If skip returns true, then the dedupe check is skipped.

  • key : (url, opts) => string

Returns a key that is used to identify the request.

  • clear (url, opts) => boolean

Clears the cache if true.

  • invalidate (url, opts) => string | RegExp | Array<string | RegExp> | null

Removes url(s) matching the string or RegExp from the cache. Can use an array to invalidate multiple values.

  • condition response => boolean

If false then the response will not be added to the cache.

  • flagResponseOnCacheHit string

If set, a Response returned from the cache whill be flagged with a property name equal to this option.

Usage

import wretch from 'wretch'
import { throttlingCache } from 'wretch-middlewares'

wretch().middlewares([
    throttlingCache({
        /* Options - defaults below */
        throttle: 1000,
        skip: (url, opts) => opts.skipCache || opts.method !== 'GET',
        key: (url, opts) => opts.method + '@' + url,
        clear: (url, opts) => false,
        invalidate: (url, opts) => null,
        condition: response => response.ok,
        flagResponseOnCacheHit: '__cached'
    })
])./* ... */

Delay

Delays the request by a specific amount of time.

Options

  • time : milliseconds

The request will be delayed by that amount of time.

Usage

import wretch from 'wretch'
import { delay } from 'wretch-middlewares'

wretch().middlewares([
    delay(1000)
])./* ... */

wretch-middlewares's People

Contributors

asoltys avatar dependabot[bot] avatar elbywan avatar gutenye avatar mikefowler avatar t3chguy avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

wretch-middlewares's Issues

retry not work

When the request fails, no retry is performed when net::ERR_HTTP2_PING_FAILED is returned

Needless Response.clone() calls

I have noticed that both the retry and dedupe modules call response.clone() at least once for each request, even when the body is not read. This can be harmful to performance in applications such as serverless functions (eg. Cloudflare Workers), in situations where the body is never read or is streamed through in the function's response.

I would recommend to remove these response.clone() calls. Instead a disclaimer could be added in the documentation reminding the user that, if their until or onRetry function reads the response body, they should call response.clone() themselves. I can create a PR with this changed, but wanted to get feedback on such a change first.

node-fetch polyfill causes indefinitely pending promises when using the retry middleware

Hey, I am working on a NodeJS project (using TypeScript) and I had the following code roughly:

const data = await wretch(url)
        .middlewares([
          retry()
        ])
        .get()
        .json();

And having the middleware in there causes an infinitely pending await.

At first I thought I did something wrong, and tried different things.

For that I changed it to the following:

const response = await wretch(url)
  .middlewares([
    retry()
  ])
  .get()
  .res();

let data;
try {
  data = await response.json();
} catch (e) {
  console.log(e);
}

This now correctly returns a response object, where I can see that the request was successful.

But as soon as I call .json() I once again have a indefinitely hanging promise. The same is true for other Promises based resolvers for the body like .text().

I setup the polyfills for NodeJS as described on the main repository.

So I had the idea that it might be caused by the node-fetch polyfill. So I compiled the Typescript files, and ran it with the flag --experimental-fetch (Node version 17.5.0) and indeed, it works flawlessly when using the built-in fetch function.

But the problem is, in my project setup using this experimental flag is rather awkward and I would prefer to not use it, while keeping the middleware in there.

So my final question is:

Do you have any idea how to fix this (/circumvent it). Maybe a different resolver can already give me what I want, but so far I didn't get anything working which I wanted to work.


I want to mention two more things:

The delay middleware works without any issues.

Also the request I am doing does not do a single retry, but is successful in the first try. I also didn't consume the Request in any way.

How to return the original error

Apologies for the basic question and thank you for this code

How does one retrieve the original raised error here? If I am making a request to an endpoint and that endpoint is returning a 403 my request will fail after e.g. 3 attempts and the raised error will be "max attempts exceeded" in the catch block - how do we instead raise the error in a forbidden block:

client
            .url('cs_auth')
            .post({ id })
            .forbidden(() => {
                // This block will never be run even though it should be
                setTryingActivation(false);
                setError({severity: 'error', message: "id number is not preapproved. Please contact your administrator"})
            })
            .json((json) => {
                setId(json.id);
                setTryingActivation(false);
            })
            .catch((err) => {
                // This block will be the only one run even though the error is a 403
                setTryingActivation(false);
                console.log(err)
                return setError({ severity: 'error', message: err.toString() });
            });

Make onRetry asynchronous

I would like to change the onRetry method and make it asynchronous. For example it would be nice to refresh an authentication token before retrying the request. Do you plan on adding this feature?

Retry without returning error?

This seems like a strange question, but is it possible to get the retry middleware to retry a request without returning the request error, unless it fails the maximum number of retries?

Retry while user is offline

I am trying to implement a use case when a user performs a request without internet. When I use the retry middleware, the retry is not called if the user isOffline. How would you implement it?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.