query-with-axios
Version:
A utility package for making API requests with Axios and managing queries and mutations using TanStack Query.
82 lines (77 loc) • 2.96 kB
JavaScript
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/index.ts
var index_exports = {};
__export(index_exports, {
InitAxiosRoute: () => InitAxiosRoute,
useMutationWithAxios: () => useMutationWithAxios,
useQueryWithAxios: () => useQueryWithAxios
});
module.exports = __toCommonJS(index_exports);
// src/api/useQueryAxios.ts
var import_vue_query = require("@tanstack/vue-query");
// src/api/util/Route.ts
var InitAxiosRoute = class {
static axiosRoute = {};
// Generic fallback type
// Create a route with a specified type
static createAxiosRoute(axiosRouteInit) {
this.axiosRoute = axiosRouteInit;
}
static getApiRoute = () => {
if (!Object.keys(this.axiosRoute).length) {
throw new Error(
"Axios route has not been initialized. Call createAxiosRoute first."
);
}
return this.axiosRoute;
};
};
// src/api/useQueryAxios.ts
var sendRequest = async (route, routeMethod, payload) => {
const axiosRoute = InitAxiosRoute.getApiRoute();
const query = axiosRoute[route][routeMethod];
return query(payload);
};
var useQueryWithAxios = (route, routeMethod, payload, options) => {
return (0, import_vue_query.useQuery)({
// Generate a unique query key based on the route, method, and payload. This is crucial for caching and invalidation.
queryKey: [`${route}-${String(routeMethod)}`, payload],
// The query function that fetches the data. Calls the sendRequest function.
queryFn: () => sendRequest(route, routeMethod, payload?.value),
// Spread any additional options provided by the user.
...options
});
};
var useMutationWithAxios = (route, routeMethod, options) => {
return (0, import_vue_query.useMutation)({
// Generate a unique mutation key based on the route and method.
mutationKey: [`${route}-${String(routeMethod)}`],
// The mutation function that performs the API request. Calls the sendRequest function.
mutationFn: (data) => sendRequest(route, routeMethod, data),
// Spread any additional options provided by the user.
...options
});
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
InitAxiosRoute,
useMutationWithAxios,
useQueryWithAxios
});
;