query-with-axios
Version:
A utility package for making API requests with Axios and managing queries and mutations using TanStack Query.
53 lines (50 loc) • 1.79 kB
JavaScript
// src/api/useQueryAxios.ts
import { useMutation, useQuery } from "@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 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 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
});
};
export {
InitAxiosRoute,
useMutationWithAxios,
useQueryWithAxios
};