vlki / refresh-fetch

Wrapper around fetch capable of graceful authentication token refreshing.
MIT License
84 stars 12 forks source link

Node-fetch functionality #16

Closed MilamBardo closed 3 years ago

MilamBardo commented 3 years ago

Hi, I'm a complete newbie here, so not sure if this is possible, but:

I am using this with node-fetch, otherwise the calls to "fetch" are undefined. So I am just adding

const fetch = require('node-fetch');

to both fetchJSON.js and configureRefreshFetch,js

Is it possible to develop something where you somehow inject the fetch client? I know that fetch-cookie does it with something like the following:

module.exports = function fetchCookieDecorator (fetch, jar, ignoreError = true) { fetch = fetch || window.fetch

and then you just inject it when requiring fetch-cookie:

var nodefetch = require('node-fetch') const tough = require('tough-cookie') let personalJar = new tough.CookieJar(); const fetch = require('fetch-cookie')(nodefetch, personalJar, false)

Like I say, not sure if possible, but thought I would just ask...

vlki commented 3 years ago

Hey, I see what you mean. fetchJSON function expects global fetch available, but to configureRefreshFetch function you pass the fetch you want to decorate. So you should be able to do it by defining fetch for configureRefreshFetch yourself. Basically when passing the fetch to configureRefreshFetch you should only make sure that the returned promise is rejected on error response.

Something like:

const nodefetch = require('node-fetch');

const fetchRejecting = (url, options) => {
    return nodefetch(url, options).then(response =>
        response.ok ? response : Promise.reject(response)
    )
}

// ... setup according to the readme
MilamBardo commented 3 years ago

Ok, great, thanks. I'll try that.