query-routing
v1.1.1
Published
A CLI tool that generates a complete API structure with React Query (TanStack Query), Axios interceptors, and full TypeScript support. Zero configuration, maximum type safety.
Maintainers
Readme
Create API Setup
A zero-configuration CLI tool that generates a production-ready, strongly-typed API layer for your React applications.
Stop writing boilerplate code. query-routing scaffolds a complete architectural foundation for your API calls, combining Axios, TanStack Query (React Query), and TypeScript into a scalable, modular structure.
✨ Features
- ⚡️ Instant Scaffolding: Sets up a full
api/directory structure in seconds. - 📄 OpenAPI/Swagger Integration: Automatically detects your spec file (
openapi.yaml,openapi.yml, oropenapi.json) to auto-generate routes and types. - 🧠 Intelligent Detection: Automatically detects if you are using a
src/folder and places files accordingly. - 📦 Dependency Management: Checks for required packages (
axios,@tanstack/react-query) and installs them if missing. - 🛡️ Strong Typing: Generates strict interfaces for Requests (
req), Responses (res), and Routes. - 🔌 Interceptors Ready: Pre-configured Axios instance with request/response interceptors (perfect for Auth headers).
- ⚛️ React Hooks: Includes generic
useQueryanduseMutationwrappers for consistent data fetching.
🚀 Quick Start
You don't need to install this package globally. Just run it within your existing React project:
npx query-routing
🔥 For Super Fast Generation (OpenAPI)
To enable the automatic generation of types and routes from your backend:
- Ensure your OpenAPI spec file is named exactly one of the following:
openapi.yamlopenapi.ymlopenapi.json
- Place it in the root of your project.
- Run the command!
What happens next?
- The CLI checks your
package.jsonfor dependencies. - It asks to install missing packages (Axios, TanStack Query) if needed.
- It detects your
openapifile and parses your endpoints. - It generates a structured
apifolder in your project root orsrc/api(ifsrcexists).
📂 The Generated Structure
After running the command, your project will possess this modular architecture:
src/api/
├── 📂 axios-config/
│ └── interceptor.ts # Centralized Axios instance & error handling
├── 📂 enum/
│ └── api-path.ts # String constants for API endpoints
├── 📂 hook/
│ └── hook.ts # Generic useQueryWithAxios & useMutationWithAxios
├── 📂 req/
│ └── req.types.ts # Request payload interfaces
├── 📂 res/
│ └── res.types.ts # Response payload interfaces
├── 📂 types/
│ ├── api.types.ts # Generic Response Wrappers (IAxiosData)
│ └── route.type.ts # The contract definitions for your routes
└── api-route.ts # The runtime implementation of the routes
🛠 Usage Guide
Once the files are generated, here is how you use the system in your day-to-day development.
1. Consuming Data (The Hook)
We provide a typed wrapper around React Query. You don't need to write fetch functions manually in your components.
import React from "react";
import { useQueryWithAxios } from "./src/api/hook/hook";
export function UserList() {
// "auth" is the route group, "getUserInfo" is the method
const { data, isLoading, error } = useQueryWithAxios("auth", "getUserInfo");
if (isLoading) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;
return (
<ul>
{/* data.data contains your actual payload */}
{data?.data.map((user) => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}2. Performing Mutations
For POST, PUT, or DELETE requests:
import { useMutationWithAxios } from "./src/api/hook/hook";
function CreateUserButton() {
const { mutate, isPending } = useMutationWithAxios("auth", "createUser");
const handleClick = () => {
mutate(
{ name: "John Doe", email: "[email protected]" }, // Strictly typed payload
{
onSuccess: (response) => {
console.log("User created:", response.data);
},
}
);
};
return (
<button onClick={handleClick} disabled={isPending}>
Create User
</button>
);
}🧩 Workflow: Adding a New Route
To add a new API endpoint, follow this strict (but rewarding) cycle:
- Define Types:
- Add request params to
req/req.types.ts - Add response shape to
res/res.types.ts
- Define Contract:
- Update
types/route.type.tsto map the method name to the types.
- Implement:
- Add the Axios call in
api-route.tsusingApiPathconstants.
Example:
// 1. types/route.type.ts
export interface IPostRoute {
getPosts: () => IResponse<IPost[]>; // Define the signature
}
// 2. api-route.ts
export const ApiRoute: IAxiosRoute = {
posts: {
getPosts: () => api.get(ApiPath.POSTS), // Implement it
},
// ...
};⚙️ Configuration
Interceptors & Auth
Go to src/api/axios-config/interceptor.ts. This is where you inject tokens:
api.interceptors.request.use((config) => {
const token = localStorage.getItem("token");
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
});Base URL
Ensure your environment variables are set. The default configuration looks for:
const BASE_URL = import.meta.env.VITE_API_URL || process.env.REACT_APP_API_URL;⚖️ License
MIT License
Copyright (c) 2025 Abdelhadi Alkayal
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
