dirent-router
v1.0.9
Published
Generate routes from a directory
Readme
dirent-router
Generate routes from a directory
Install
npm install dirent-router
# or
pnpm install dirent-routerRoute Directory Structure
Each .ts file in your routes directory becomes an endpoint. Exported function names correspond to HTTP methods (get, post, put, delete, etc.).
index.tsfiles map to the parent directory path- Other
.tsfiles map to a path segment matching their filename - Directory names wrapped in brackets (e.g.,
[id]) become route variables
Example:
routes/
├── index.ts → /
├── companies/
│ ├── index.ts → /companies
│ ├── search.ts → /companies/search
│ └── [id]/
│ └── index.ts → /companies/[id]// routes/index.ts
export const get = () => {
return 'foo';
}
// routes/companies/index.ts
export const get = () => {
return [{ id: 'a' }, { id: 'b' }];
}
export const post = () => {
return { ok: true };
}
// routes/companies/search.ts
export const get = (searchQuery: string) => {
return { searchQuery };
}
// routes/companies/[id]/index.ts
export const get = (id: string) => {
return { id };
}Usage
Integration
import fs from "fs";
import { getRoutes } from "dirent-router";
const routes = await getRoutes({
routesDir: "./path/to/your/routes",
});
console.log(
JSON.stringify(
routes,
(_, v) => (typeof v === "function" ? `${v.name}(...)` : v),
2,
),
);
// Output example
[
{
"filepath": "sample-routes/companies/[id]",
"relativepath": "companies/[id]",
"endpoint": "/companies/[id]",
"args": [
{
"type": "path",
"value": "companies"
},
{
"type": "variable",
"value": "id"
}
],
"methods": {
get: "[Function]"
}
}
]CLI
dirent-router ./path/to/your/routes