Closed devlzcode closed 1 year ago
Hey @agent-ly,
I see that the retry middleware actually does a "beforeResponse" kind of step and the behavior of it is unclear to me. I think it'd be cleaner if an API was introduced to handle this, maybe for addons as they already support beforeRequest
I don't think that a specific API is needed, the behaviour is actually quite simple when using middlewares:
const myMiddleware = delay => next => async (url, opts) => {
// Code runs here before the request is sent
const response = await next(url, opts) // fetches
// Code runs here after the response is received
}
Note: using .defer
would be another and maybe easier alternative
how they can be stacked together or the order of execution
The execution order is pretty straightforward, it matches the order of insertion (which is standard for "middlewares").
const dummyMiddleware = label => next => async (url, opts) => {
console.log("Before: ", label)
const res = await next(url, opts)
console.log("After: ", label)
return res
}
const w = wretch().middlewares([
dummyMiddleware("a"),
dummyMiddleware("b"),
dummyMiddleware("c"),
dummyMiddleware("d"),
])
w.get("https://jsonplaceholder.typicode.com/posts/1").res(console.log)
/*
Before: a
Before: b
Before: c
Before: d
After: d
After: c
After: b
After: a
*/
@elbywan Your post clears up a lot, is there anything else I should be aware of?
Your post clears up a lot
Glad I could help 😄
is there anything else I should be aware of?
Hard for me to guess, do you have any other questions on the same topic?
Hard for me to guess, do you have any other questions on the same topic?
Hm, I guess defer could be explained further? Not quite sure what it does or its intent since it sounds like it acts like a middleware?
You can check the documentation here: https://elbywan.github.io/wretch/api/interfaces/index.Wretch.html#defer
Helped me as I couldn't figure out where to put the magic incantations to make middleware async as I need to fetch in it.
Now I know.
I don't think more stuff is needed. From what I recall you can't tinker with the request itself in an "addon", but you can in the middleware, but I just tried both ways around and took the one which worked.
I see that the
retry
middleware actually does a "beforeResponse" kind of step and the behavior of it is unclear to me. I think it'd be cleaner if an API was introduced to handle this, maybe for addons as they already supportbeforeRequest
, and insight on how they can be stacked together or the order of execution (like right now, does retry execute after throttlingCache if index is higher or lower?)