benjamine / fetch-wrap Goto Github PK
View Code? Open in Web Editor NEWextend WHATWG fetch wrapping it with middlewares
License: MIT License
extend WHATWG fetch wrapping it with middlewares
License: MIT License
Hi, I'm having a problem serving my webpack bundle to older browsers. I'm using your library but because of one little "const" in middleware.js it breaks.
Line 150 in 91faed9
Would it be possible to replace "const" here with var?
Can you tell me how can I connect this wrapper with Redux. I want to have in separate file this wrapper and I need to dispatch some actions inside function for example for adding header.
File should looks like this but I'm getting dispatch is not defined error:
import { authGetToken } from "../store/actions/index";
const fetchWrap = require("fetch-wrap");
customFetch = fetchWrap(fetch, [
function(url, options, fetch) {
// add headers
console.log("In fetch wrap!");
dispatch(authGetToken())
.then(token => {
return fetch(
url,
fetchWrap.merge({}, options, {
headers: {
Authorization: "bearer " + token
}
})
);
})
.catch(err => {
console.log("Error while trying to get token with AuthGetToken");
});
},
]);
export default customFetch;
Using the header object in a fetch call
headers: new Headers(
{
"Content-Type": "application/json",
}
),
instead of just
headers: {
"Content-Type": "application/json",
}
will cause the merging of headers as show in the documentation to fail. Only the header(s) given in the fetch call will be used.
If a fix or warning for this is not desirable, could it be at least mentioned in the documentation? Depending on which solution you prefer I will gladly create a pull request.
I wonder how one could make this a little bit more type-safe by having the middleware actually know the types of the arguments and the supposed return value (Promose<Response>
).
I have started with this:
// This should be exported by "fetch-wrap" as a type
type FetchFunction = typeof fetch
export function logHeaders() {
return function(url: string, options:RequestInit = {}, fetch: FetchFunction):Promise<Response> {
}
}
I wonder if the usage of lodash/merge is obsolete for the operations most middlewares do here?
They usually don't do deep merges so couldn't
return fetch(url, extendedFetch.merge({}, options, {
headers: {
"Authorization": "Bearer ...",
}
}))
be replaced with:
return fetch(url, {
...options,
headers: {
...options.headers,
"Authorization": "Bearer ...",
}
}))
it.only("should not matter", () => {
const options = {
body: "Test",
headers: {
"Accept": "text/plain",
},
}
expect(extendFetch.merge({}, options, {
headers: {
"Content-Type": "text/plain",
},
})).toEqual({
...options,
headers: {
...options.headers,
"Content-Type": "text/plain",
},
})
})
I was curious about the order in which middleware is being applied by fetch-wrap. This is an awesome library that we use heavily for our projects. We ran into a curious case where it seems that custom middleware would need to be applied in reverse-order, bottom-to-top, instead of top-to-bottom. For example:
const newFetch = fetchWrap(originalFetch, [
doFirstThing(),
doSecondThing(),
doThirdThing()
]);
This would first call doThirdThing
, then proceed backwards. Is this the intended behavior? I would hesitate to call it a "bug", since I see the test expectations in the repository that mimic these results. I have forked the repo and created a new test to better illustrate what I mean:
If this is something that you and the community would like to have adjusted, I would be happy to take a stab at it and submit a pull request.
I'd like to implement an OpenID-Connect refresh logic inside a middleware that adds an Access Token to a request and reacts on 401 responses by fetching a new access token and repeating the request with the new token.
However, inside the middleware I only have access to the "next" middleware in the chain and not the "start" of the middleware chain, so middleware that would transform bodies would not work.
function middleware() {
return function(url:string, options: RequestInit, next: FetchFunction) {
const fetch = next
if (accessToken) {
options = {
...options,
headers: {
...options.headers,
"Authorization": "Bearer " + accessToken,
},
}
}
return next(url, options).then(response => {
if (response.status === 401 && refreshToken) {
return fetch(tokenURI, {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
body: {
grant_type: "refresh_token",
client_id: clientId,
client_secret: clientSecret,
refresh_token: refreshToken,
},
})
} else {
return response
}
})
}
}
I have a sendFormEncoded
middleware that should take care of converting an object body to urlencoded but its not triggered in my request to fetch a new access token. Any idea how to hand in the original start of the middle ware chain into each middleware?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.