nuxt-advanced-fetch
Version:
Enhances Nuxt 3 $fetch with lifecycle handlers, dynamic management, and custom fetch instances for modular API requests.
77 lines (76 loc) • 2.26 kB
JavaScript
import { defineNuxtPlugin } from "#app";
export default defineNuxtPlugin({
name: "api",
enforce: "pre",
setup() {
const globalHandlers = {
onRequest: [],
onRequestError: [],
onResponse: [],
onResponseError: []
};
function callMaybeArray(maybeArray, arg) {
if (Array.isArray(maybeArray)) {
maybeArray.forEach((fn) => fn(arg));
} else if (typeof maybeArray === "function") {
maybeArray(arg);
}
}
function enhanceInstance(instance, handlers = globalHandlers) {
return Object.assign(
(url, options) => {
return instance(url, {
...options,
onRequest: (context) => {
handlers.onRequest.forEach(
(handler) => handler(context)
);
callMaybeArray(options?.onRequest, context);
},
onRequestError: (error) => {
handlers.onRequestError.forEach(
(handler) => handler(error)
);
callMaybeArray(options?.onRequestError, error);
},
onResponse: (context) => {
handlers.onResponse.forEach(
(handler) => handler(context)
);
callMaybeArray(options?.onResponse, context);
},
onResponseError: (error) => {
handlers.onResponseError.forEach(
(handler) => handler(error)
);
callMaybeArray(options?.onResponseError, error);
}
});
},
{
addHandler(type, handler) {
handlers[type].push(handler);
},
removeHandler(type, handler) {
const index = handlers[type].indexOf(handler);
if (index !== -1) handlers[type].splice(index, 1);
},
create(...args) {
const newInstance = instance.create(...args);
return enhanceInstance(newInstance, {
onRequest: [],
onRequestError: [],
onResponse: [],
onResponseError: []
});
}
}
);
}
return {
provide: {
api: enhanceInstance($fetch)
}
};
}
});