@galaxy-stack/orbit-throttler
v0.1.9
Published
Rate limiting module for Orbit framework
Readme
@galaxy-stack/orbit-throttler
Mô tả
Module rate limiting cho Orbit để bảo vệ API khỏi abuse.
Tính năng chính
1. Throttle Decorator
import { Throttle, UseGuards, ThrottlerGuard } from '@galaxy-stack/orbit-throttler';
@Controller('api')
@UseGuards(ThrottlerGuard)
class ApiController {
@Get('data')
@Throttle({ limit: 10, ttl: 60 }) // 10 requests per 60 seconds
getData() {
return { data: 'value' };
}
}2. Skip Throttle
@SkipThrottle() // Skip throttling for this route
@Get('health')
healthCheck() {
return { status: 'ok' };
}Cấu hình Module
Basic
import { ThrottlerModule } from '@galaxy-stack/orbit-throttler';
@Module({
imports: [
ThrottlerModule.forRoot({
ttl: 60, // Time window in seconds
limit: 100, // Max requests per window
}),
],
})
class AppModule {}Multiple Limits
ThrottlerModule.forRoot({
throttlers: [
{ name: 'short', ttl: 1, limit: 3 }, // 3 req/sec
{ name: 'medium', ttl: 60, limit: 100 }, // 100 req/min
{ name: 'long', ttl: 3600, limit: 1000 }, // 1000 req/hour
],
})Redis Storage
ThrottlerModule.forRoot({
storage: new RedisThrottlerStorage({
url: 'redis://localhost:6379',
}),
ttl: 60,
limit: 100,
})Throttle Options
interface ThrottleOptions {
limit: number; // Max requests
ttl: number; // Time window (seconds)
key?: string; // Custom key generator
}Custom Key Generator
@Throttle({
limit: 10,
ttl: 60,
keyGenerator: (context) => {
const request = context.switchToHttp().getRequest();
return request.user?.id || request.ip;
},
})Response Headers
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1640000000Error Response (429)
{
"statusCode": 429,
"message": "Too Many Requests",
"retryAfter": 45
}Per-User Limits
@Throttle({
limit: (context) => {
const user = context.switchToHttp().getRequest().user;
return user?.isPremium ? 1000 : 100;
},
ttl: 60,
})