Skip to content

GraphStats/Routly

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

19 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Routly

A modern, feature-rich web framework for Node.js with TypeScript support. Unlike Express, Routly comes with batteries included - validation, CORS, rate limiting, and more are built right in.

TryHard Dev

✨ Features

  • πŸš€ Lightweight: Built on Node.js native http module
  • πŸ›£οΈ Advanced Routing: Support for all HTTP methods, route parameters, and route groups
  • ⚑ Async/Await Native: First-class support for async handlers
  • πŸ”’ Built-in Validation: No need for external validation libraries
  • 🌐 CORS Middleware: Integrated CORS support
  • πŸ›‘οΈ Rate Limiting: Protect your API from abuse
  • πŸͺ Cookie Parser: Parse and set cookies easily
  • πŸ“ Static Files: Serve static files with ETag support
  • πŸ“¦ Body Parsing: JSON and URL-encoded body parsing
  • 🎯 Route Groups: Organize routes with prefixes and shared middleware
  • πŸ”§ Error Handling: Centralized error handling with custom errors
  • πŸ“ TypeScript: Full TypeScript support with complete type definitions

πŸ“¦ Installation

npm install routly

πŸš€ Quick Start

import { Routly, bodyParser } from 'routly';

const app = new Routly();

// Middleware
app.use('/', bodyParser.json());

// Routes
app.get('/', (req, res) => {
  res.json({ message: 'Hello Routly!' });
});

app.post('/users', (req, res) => {
  res.status(201).json({ user: req.body });
});

// Start server
app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});

πŸ“š Documentation

HTTP Methods

Routly supports all standard HTTP methods:

app.get('/users', handler);
app.post('/users', handler);
app.put('/users/:id', handler);
app.patch('/users/:id', handler);
app.delete('/users/:id', handler);
app.options('/users', handler);

Route Groups

Organize routes with shared prefixes and middleware:

app.group('/api/v1', (group) => {
  // Middleware for this group
  group.use('/', authMiddleware);
  
  // Routes
  group.get('/users', getUsers);
  group.post('/users', createUser);
  group.get('/users/:id', getUser);
});

Built-in Validation

Validate request data without external libraries:

import { validators } from 'routly';

app.post('/users', validators.body({
  name: { type: 'string', required: true, min: 3, max: 50 },
  email: { type: 'email', required: true },
  age: { type: 'number', min: 18, max: 120 },
}), (req, res) => {
  res.json({ user: req.body });
});

Validation Rules:

  • type: 'string' | 'number' | 'boolean' | 'email' | 'url' | 'array' | 'object'
  • required: boolean
  • min: minimum length/value
  • max: maximum length/value
  • pattern: RegExp
  • custom: custom validation function
  • message: custom error message

CORS Middleware

import { cors } from 'routly';

app.use('/', cors({
  origin: '*', // or array of origins, or function
  methods: ['GET', 'POST', 'PUT', 'DELETE'],
  allowedHeaders: ['Content-Type', 'Authorization'],
  credentials: true,
}));

Rate Limiting

import { rateLimit } from 'routly';

app.use('/api', rateLimit({
  windowMs: 60000, // 1 minute
  max: 100, // 100 requests per minute
  message: 'Too many requests',
}));

Cookie Parser

import { cookieParser } from 'routly';

app.use('/', cookieParser());

app.get('/set-cookie', (req, res) => {
  res.cookie('user', 'john', { 
    maxAge: 3600000, 
    httpOnly: true 
  });
  res.json({ message: 'Cookie set' });
});

app.get('/get-cookie', (req, res) => {
  res.json({ cookies: req.cookies });
});

Static Files

import { serveStatic } from 'routly';
import * as path from 'path';

app.use('/public', serveStatic(path.join(__dirname, 'public'), {
  maxAge: 86400, // 1 day cache
  etag: true,
}));

Body Parsers

import { bodyParser } from 'routly';

// JSON parser
app.use('/', bodyParser.json({ limit: 5 * 1024 * 1024 })); // 5MB limit

// URL-encoded parser
app.use('/', bodyParser.urlencoded({ limit: 5 * 1024 * 1024 }));

Error Handling

import { errorHandler, asyncHandler, createError } from 'routly';

// Async route with automatic error handling
app.get('/async', asyncHandler(async (req, res) => {
  const data = await fetchData();
  res.json(data);
}));

// Throw custom errors
app.get('/error', (req, res) => {
  throw createError.badRequest('Invalid input');
});

// Error handler middleware (must be last)
app.use('/', errorHandler({ 
  log: true,
  showStack: process.env.NODE_ENV !== 'production'
}));

Available error creators:

  • createError.badRequest(message) - 400
  • createError.unauthorized(message) - 401
  • createError.forbidden(message) - 403
  • createError.notFound(message) - 404
  • createError.conflict(message) - 409
  • createError.internal(message) - 500

Request Object

interface Request {
  query: { [key: string]: string | string[] };
  params: { [key: string]: string };
  body?: any;
  cookies?: { [key: string]: string };
  ip?: string;
  
  // Helper methods
  is(type: string): boolean;
  get(header: string): string | string[] | undefined;
  accepts(...types: string[]): string | false;
}

Response Object

interface Response {
  status(code: number): this;
  json(body: any): void;
  send(body: string | Buffer): void;
  redirect(url: string, status?: number): void;
  cookie(name: string, value: string, options?: CookieOptions): this;
  sendFile(path: string): void;
}

🎯 Why Routly over Express?

Feature Routly Express
TypeScript Native βœ… Built-in ❌ Needs @types
Validation βœ… Built-in ❌ Needs express-validator
CORS βœ… Built-in ❌ Needs cors package
Rate Limiting βœ… Built-in ❌ Needs express-rate-limit
Cookie Parser βœ… Built-in ❌ Needs cookie-parser
Async/Await βœ… Native support ⚠️ Needs wrappers
Route Groups βœ… Built-in ❌ Manual setup
Modern API βœ… Clean & intuitive ⚠️ Legacy patterns

πŸ“– Examples

Check out the examples directory for complete working examples:

🀝 Contributing

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

πŸ“„ License

ISC

πŸ”— Links

About

Un package NPM, comme express, mais en mieux

Resources

Stars

Watchers

Forks

Packages

No packages published

Contributors 2

  •  
  •