fastify-auto-routes

Fastify Auto Add Routes

This project is maintained by owservable

owservable

@owservable/fastify-auto-routes

Automatically register Fastify routes from your file system structure. This library scans your routes directory and automatically registers all route files with your Fastify instance, supporting both TypeScript and JavaScript files.

๐Ÿš€ Features

๐Ÿ“ฆ Installation

npm install @owservable/fastify-auto-routes

or

yarn add @owservable/fastify-auto-routes

or

pnpm add @owservable/fastify-auto-routes

๐Ÿ”ง Usage

Basic Setup

import fastify from 'fastify';
import { addFastifyRoutes } from '@owservable/fastify-auto-routes';

const server = fastify();

// Add all routes from the routes directory
addFastifyRoutes(server, './routes');

// Start the server
server.listen({ port: 3000 });

With Verbose Logging

import fastify from 'fastify';
import { addFastifyRoutes } from '@owservable/fastify-auto-routes';

const server = fastify();

// Add routes with verbose logging enabled
addFastifyRoutes(server, './routes', true);

server.listen({ port: 3000 });

Route File Examples

Single Route File (routes/users.ts)

export default {
  method: 'GET',
  url: '/users',
  handler: async (request, reply) => {
    return { users: [] };
  }
};

Multiple Routes File (routes/posts.ts)

export default [
  {
    method: 'GET',
    url: '/posts',
    handler: async (request, reply) => {
      return { posts: [] };
    }
  },
  {
    method: 'POST',
    url: '/posts',
    handler: async (request, reply) => {
      return { message: 'Post created' };
    }
  }
];

With Schema and Tags (routes/api/v1/products.ts)

export default {
  method: 'GET',
  url: '/api/v1/products',
  schema: {
    tags: ['products'],
    summary: 'Get all products',
    response: {
      200: {
        type: 'object',
        properties: {
          products: { type: 'array' }
        }
      }
    }
  },
  handler: async (request, reply) => {
    return { products: [] };
  }
};

Using with Action Routes

import { addActionRoutes } from '@owservable/fastify-auto-routes';

// Add action-based routes
addActionRoutes(server, './actions');

Route Mapping and Debugging

import { RoutesMap } from '@owservable/fastify-auto-routes';

// Get all registered routes
const allRoutes = RoutesMap.list();
console.log(allRoutes);

// Get routes for specific method
const getRoutes = RoutesMap.getRoutes('GET');
console.log(getRoutes);

// Get all methods
const methods = RoutesMap.getMethods();
console.log(methods);

๐Ÿ“ File Structure Conventions

The library follows these conventions:

routes/
โ”œโ”€โ”€ index.ts          โ†’ /
โ”œโ”€โ”€ users.ts          โ†’ /users
โ”œโ”€โ”€ posts.ts          โ†’ /posts
โ”œโ”€โ”€ api/
โ”‚   โ”œโ”€โ”€ v1/
โ”‚   โ”‚   โ”œโ”€โ”€ users.ts  โ†’ /api/v1/users
โ”‚   โ”‚   โ””โ”€โ”€ posts.ts  โ†’ /api/v1/posts
โ”‚   โ””โ”€โ”€ v2/
โ”‚       โ””โ”€โ”€ users.ts  โ†’ /api/v2/users
โ””โ”€โ”€ admin/
    โ””โ”€โ”€ dashboard.ts  โ†’ /admin/dashboard

๐Ÿ”ง Configuration Options

Route Object Properties

interface RouteOptions {
  method: string | string[];        // HTTP method(s)
  url: string;                      // Route URL
  handler: Function;                // Route handler function
  schema?: object;                  // JSON schema for validation
  preHandler?: Function | Function[]; // Pre-handler hooks
  onRequest?: Function | Function[];  // Request hooks
  // ... other Fastify route options
}

Auto-Generated Properties

The library automatically adds/fixes these properties:

๐Ÿ“š API Documentation

addFastifyRoutes(fastify, folder, verbose?)

Recursively scans and registers all route files in the specified folder.

Parameters:

addActionRoutes(fastify, folder, verbose?)

Registers action-based routes from the specified folder.

Parameters:

RoutesMap

Static class for managing registered routes.

Methods:

cleanRelativePath(rootFolder, absolutePath, extension)

Utility function to generate clean URLs from file paths.

Parameters:

Returns: Clean relative path suitable for URL

๐Ÿ—๏ธ Requirements

๐Ÿงช Testing

npm test

๐Ÿ“– Documentation

๐Ÿ“„ License

Licensed under The Unlicense.

๐Ÿค Contributing

Contributions are welcome! Please feel free to submit a Pull Request.