-
Notifications
You must be signed in to change notification settings - Fork 151
Description
Describe the feature
I need to log some data on each request/response, transform the request url (e.g. /pets/{petId} -> /pets/1) etc.
If I add onRequest to the $fetch.create and then add onRequest to the actual client:
const $myFetch = $fetch.create({
onRequest() {
// Log data
}
})
$myFetch({
onRequest() {} // logging is lost
})handler from $fetch.create will be replaced by the handler from $myFetch.
To get around this we need to create the wrapper around $fetch:
function $myFetch(url: string, options: FetchOptions) {
return $fetch(url, {
...options,
onRequest(ctx) {
// Log data and transform url
// ...
return options.onRequest?.(ctx)
}
})
}What do you think about adding some sort of interceptors "merging strategy" option?
It can be done based on the idea of this PR #353.
If we treat interceptors as an array, we can allow merging arrays from $fetch and $fetch.create. So that interceptors from $fetch and $fetch.create can be enforced to append or prepend to the resulting array of interceptors (similar to Nuxt plugins):
const $myFetch = $fetch.create({
onRequest: [
(ctx) => { /* Handler 1 */ }, // same as "enforce: 'default'"
{
enforce: 'post',
handler: (ctx) => { /* Handler 2 */ }
}
]
})
$myFetch({
onRequest: [
// Will be appended
(ctx) => { /* Handler 3 */ },
// If you need to prepend in some scenarios
{
enforce: 'pre',
handler: (ctx) => { /* Handler 4 */ }
}
]
})
// Interceptors will be executed in this order:
/*
Handler 4
Handler 1
Handler 3
Handler 2
*/Alternative Original idea
const $myFetch = $fetch.create({
onRequest: {
strategy: 'before', // 'overwrite' | 'before' | 'after' | 'manual', 'overwrite' by default
handler(ctx) { ... }
}
})
$myFetch({
onRequest() {...},
})so that interceptors from $myFetch are called after interceptors from $fetch.create.
Additional information
- Would you be willing to help implement this feature?