@athenna/http
Version:
The Athenna Http server. Built on top of fastify.
150 lines (149 loc) • 3.58 kB
JavaScript
/**
* @athenna/http
*
* (c) João Lenon <lenon@athenna.io>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
import { Route } from '#src/router/Route';
import { Macroable } from '@athenna/common';
import { RouteResource } from '#src/router/RouteResource';
export class RouteGroup extends Macroable {
constructor(routes) {
super();
this.routes = routes;
}
/**
* Define prefix for all the routes in the group.
*
* @example
* ```ts
* Route.group(() => {
*
* }).prefix('/api/v1')
* ```
*/
prefix(prefix) {
this.routes.forEach(route => this.invoke(route, 'prefix', [prefix]));
return this;
}
/**
* Define a name for all the routes in the group.
*
* @example
* ```ts
* Route.group(() => {
*
* }).name('users')
* ```
*/
name(name) {
this.routes.forEach(route => this.invoke(route, 'name', [name]));
return this;
}
/**
* Add a validator to all routes in the group.
*
* @example
* ```ts
* Route.group(() => {
*
* }).validator('auth')
* ```
*/
validator(validator) {
this.routes.forEach(route => this.invoke(route, 'validator', [validator, true]));
return this;
}
/**
* Add a middleware to all routes in the group.
*
* @example
* ```ts
* Route.group(() => {
*
* }).middleware('auth')
* ```
*/
middleware(middleware) {
this.routes.forEach(route => this.invoke(route, 'middleware', [middleware, true]));
return this;
}
/**
* Add an interceptor to all routes in the group.
*
* @example
* ```ts
* Route.group(() => {
*
* }).interceptor('response')
* ```
*/
interceptor(interceptor) {
this.routes.forEach(route => this.invoke(route, 'interceptor', [interceptor, true]));
return this;
}
/**
* Add a terminator to all routes in the group.
*
* @example
* ```ts
* Route.group(() => {
*
* }).terminator('log')
* ```
*/
terminator(terminator) {
this.routes.forEach(route => this.invoke(route, 'terminator', [terminator, true]));
return this;
}
/**
* Set up helmet options for route group.
*
* @example
* ```ts
* Route.group(() => {
*
* }).helmet({
* dnsPrefetchControl: { allow: true }
* })
* ```
*/
helmet(options) {
this.routes.forEach(route => this.invoke(route, 'helmet', [options]));
return this;
}
/**
* Set up rate limit options for route group method.
*
* @example
* ```ts
* Route.group(() => {
*
* }).rateLimit({
* max: 3,
* timeWindow: '1 minute'
* })
* ```
*/
rateLimit(options) {
this.routes.forEach(route => this.invoke(route, 'rateLimit', [options]));
return this;
}
/**
* Invokes a given method with params on the route instance or route
* resource instance.
*/
invoke(route, method, params) {
if (route instanceof RouteResource) {
route.routes.forEach(child => this.invoke(child, method, params));
return;
}
if (route instanceof RouteGroup) {
route.routes.forEach(child => this.invoke(child, method, params));
return;
}
route[method](...params);
}
}