npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

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.

Readme

Create API Setup

License: MIT npm version TypeScript

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, or openapi.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 useQuery and useMutation wrappers 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:

  1. Ensure your OpenAPI spec file is named exactly one of the following:
  • openapi.yaml
  • openapi.yml
  • openapi.json
  1. Place it in the root of your project.
  2. Run the command!

What happens next?

  1. The CLI checks your package.json for dependencies.
  2. It asks to install missing packages (Axios, TanStack Query) if needed.
  3. It detects your openapi file and parses your endpoints.
  4. It generates a structured api folder in your project root or src/api (if src exists).

📂 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:

  1. Define Types:
  • Add request params to req/req.types.ts
  • Add response shape to res/res.types.ts
  1. Define Contract:
  • Update types/route.type.ts to map the method name to the types.
  1. Implement:
  • Add the Axios call in api-route.ts using ApiPath constants.

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.