Gathering detailed insights and metrics for @universal-packages/express-controllers
Gathering detailed insights and metrics for @universal-packages/express-controllers
Gathering detailed insights and metrics for @universal-packages/express-controllers
Gathering detailed insights and metrics for @universal-packages/express-controllers
@universal-packages/core-express-controllers
Express Controllers universal-core module abstraction.
@universal-packages/express-controllers-authentication
universal-authentication implementation on top of universal-express-controllers.
@universal-packages/express-controllers-parameters
Express parameters for universal controllers
@universal-packages/core-express-controllers-authentication
Express Controllers Authentication universal-core module abstraction.
Build an express app from a conventional files tree
npm install @universal-packages/express-controllers
Typescript
Module System
Node Version
NPM Version
TypeScript (100%)
Total Downloads
0
Last Day
0
Last Week
0
Last Month
0
Last Year
0
MIT License
236 Commits
1 Watchers
1 Branches
1 Contributors
Updated on May 10, 2025
Latest Version
1.14.3
Package Id
@universal-packages/express-controllers@1.14.3
Unpacked Size
79.26 kB
Size
16.94 kB
File Count
57
NPM Version
10.8.2
Node Version
18.20.5
Published on
Nov 30, 2024
Cumulative downloads
Total Downloads
Last Day
0%
NaN
Compared to previous day
Last Week
0%
NaN
Compared to previous week
Last Month
0%
NaN
Compared to previous month
Last Year
0%
NaN
Compared to previous year
7
4
Express app builder based on decorated controller classes.
1npm install @universal-packages/express-controllers 2 3npm install express 4 5# Optional as needed 6npm install cookie-parser 7npm install cors 8npm install helmet 9npm install pug
Express app is the main interface to build an express app from the decorated controllers and also start running a web server.
1import { ExpressControllers } from '@universal-packages/express-controllers' 2 3const expressControllers = new ExpressControllers({ appLocation: './src', port: 3000 }) 4 5// Load decorated controllers and middleware 6await expressControllers.prepare() 7await expressControllers.run() 8 9// Once finishing 10await expressControllers.stop()
ExpressControllers
takes as options the same ListenOptions from net, additionally takes the following ones:
appLocation
String
Where should we look for controllers and middleware and load them?bodyParser
'json' | 'raw' | 'text' | 'urlencoded' | 'none' | ('json' | 'raw' | 'text' | 'urlencoded')[]
What body parser or body parsers use across the appcors
CorsOptions | true
Enable cors for this app, optionally passing CorsOptionscookieParser
CookieParseOptions | true
Enable cookie parser for this app, optionally passing CookieParseOptionshelmet
HelmetOptions | true
Enable helmet for this app, optionally passing HelmetOptionsviewEngine
String
Sets the view renderer (template engines)Use the base controller Class to enable your controller to use some goodies. It implement almost the same functionally as the response object so instead of doing response.something()
you can directly call your controller instance.
1import { BaseController } from '@universal-packages/express-controllers' 2 3export default class AuthController extends BaseController { 4 async index() { 5 this.status('OK').send('HOLA') 6 } 7}
Decorate your controller classes to enable them to respond to requests.
@Controller([path: string, options])
Registers a class to behave as a controller. To be able to access this.request
and this.response
inside your controller actions you can extend your controller with the BaseController
, it is not necessary but useful to access those object that way instead of using Argument Decorators
.
Controllers need to export the controller class as the default module in order to all work correctly.
path
String
default: /
This is the equivalent in pure express to: app.use($path, router)
, internally you can see a controller as an express router object so this path will be prepended to all routes.options
Map
bodyParser
'json' | 'raw' | 'text' | 'urlencoded' | 'none' | ('json' | 'raw' | 'text' | 'urlencoded')[]
What body parser use across this particular controller, use none
to disregard any body parser for this controller.1import { BaseController, Controller } from '@universal-packages/express-controllers' 2 3@Controller('/auth', { bodyParser: 'json' }) 4export default class AuthController extends BaseController {}
@ControllerUse(middleware, [options])
Enables a middleware to execute before all controller actions.
middleware
Middleware
A middleware function or middleware classoptions
Map
Any options the middleware may be prepared to receive (Class middleware)1import { BaseController, Controller, ControllerUse } from '@universal-packages/express-controllers' 2 3import RoleMiddleware from './RoleMiddleware' 4 5@Controller('/auth', { bodyParser: 'json' }) 6@ControllerUse(RoleMiddleware, { roles: ['admin'] }) 7export default class AuthController extends BaseController {}
@Action(method: HTTPVerb, path: string, [options])
Enables a controller instance method to be called when the route matches.
method
'DELETE' | 'GET' | 'HEAD' | 'OPTIONS' | 'PATCH' | 'POST' | 'PUT'
The instance method will be called if the request method matches the configured one.path
String
Path to match to call this instance method, ex: /users
or users/:id
options
Map
bodyParser
'json' | 'raw' | 'text' | 'urlencoded' | 'none' | ('json' | 'raw' | 'text' | 'urlencoded')[]
default: json
What body parser to use for this particular action, use none
to disregard any body parser for this action.1import { Action, BaseController, Controller } from '@universal-packages/express-controllers' 2 3@Controller('/auth', { bodyParser: 'json' }) 4export default class AuthController extends BaseController { 5 @Action('GET', { bodyParser: 'text' }) 6 async root() { 7 this.response.send('Hola') 8 } 9 10 @Action('POST', '/login', { bodyParser: 'json' }) 11 async login() { 12 const body = this.request.body 13 this.response.send(`login with ${JSON.stringify(body)}`) 14 } 15 16 @Action('POST', '/signup') 17 async signup() { 18 const body = this.request.body 19 this.response.send(`signup with ${JSON.stringify(body)}`) 20 } 21}
The following decorators behave the same as @Action
the only difference is that they don't take the first argument since the decorator name describe the action method itself.
@Delete(path: string, [options])
@Head(path: string, [options])
@Patch(path: string, [options])
@Post(path: string, [options])
@Put(path: string, [options])
1import { BaseController, Controller, Get, Post } from '@universal-packages/express-controllers' 2 3@Controller('/auth', { bodyParser: 'json' }) 4export default class AuthController extends BaseController { 5 @Get() 6 async root() { 7 this.response.send('Hola') 8 } 9 10 @Post('/login') 11 async login() { 12 const body = this.request.body 13 this.response.send(`login with ${JSON.stringify(body)}`) 14 } 15 16 @Post('/signup') 17 async signup() { 18 const body = this.request.body 19 this.response.send(`signup with ${JSON.stringify(body)}`) 20 } 21}
@ActionUse(middleware: Middleware, [options])
Enables a middleware to execute before a specific action.
middleware
Middleware
A middleware function or middleware classoptions
Map
Any options the middleware may be prepared to receive (Class middleware)1import { ActionUse, BaseController, Controller, Get } from '@universal-packages/express-controllers' 2 3import SecureMiddleware from './SecureMiddleware' 4 5@Controller('/auth', { bodyParser: 'json' }) 6export default class AuthController extends BaseController { 7 @Get() 8 @ActionUse(SecureMiddleware, { sometimes: true }) 9 async root() { 10 this.response.send('Hola') 11 } 12}
You can simplify the code inside your actions by using argument decorators to get certain info from the request.
@Body()
Gets the request body.
1async login(@Body() body) { 2 this.response.json({ body }) 3}
@Header(name:string)
Gets a specific header form the request header.
1async login(@Header('Authentication') header) { 2 this.response.json({ header }) 3}
@Headers()
Gets the whole headers object form request.
1async login(@Headers() headers) { 2 this.response.json({ headers }) 3}
@Param(name:string)
Gets a specific param parsed for the request.
1async login(@Param('id') id) { 2 this.response.json({ id }) 3}
@Params()
Gets the whole params parsed object from the request.
1async login(@Params() params) { 2 this.response.json({ params }) 3}
@Res()
Gets the whole response object.
1async login(@Res() response) { 2 response.json({ argument: 'yes' }) 3}
@Req()
Gets the whole request object.
1async login(@Req() request) { 2 const body = request.body 3 response.json({ argument: 'yes', body }) 4}
@Query([name: string])
Gets the whole query object or a specific property in it.
1async login(@Query() query, @Query('ordered') ordered) { 2 this.response.json({ query, ordered }) 3}
Use the base middleware Class to enable your middleware to use some goodies. It implement almost the same functionally as the response object so instead of doing response.something()
you can directly call your middleware instance.
1import { BaseMiddleware } from '@universal-packages/express-controllers' 2 3export default class AuthMiddleware extends BaseMiddleware { 4 async middleware() { 5 this.status('OK').send('HOLA') 6 } 7}
When using class middleware if the middleware ends the equest, the next()
chain is broken automatically and the request will not reach further more.
1import { BaseMiddleware } from '@universal-packages/express-controllers' 2 3export default class AuthorizationMiddleware extends BaseMiddleware { 4 async middleware() { 5 this.status('UNAUTHORIZED').end() 6 } 7}
@Middleware([path: string, options: Object])
Registers a class to behave as a middleware. To be able to access this.request
and this.response
and this.options
inside your middleware action you can extend your controller with the BaseMiddleware
, is not necessary but useful to access those object that way instead of using Argument Decorators
.
Middleware need to export the middleware class as the default module in order to all work correctly.
1import { BaseMiddleware, Middleware } from '@universal-packages/express-controllers' 2import createHttpError from 'http-errors' 3import { StatusCodes } from 'http-status-codes' 4 5@Middleware() 6export default class AuthMiddleware extends BaseMiddleware { 7 async middleware() { 8 if (!this.request['user']) throw createHttpError(StatusCodes.UNAUTHORIZED) 9 } 10}
Middleware actions can use all the Argument Decorators
plus one more to access middleware options.
@MiddlewareOptions()
Gets the options passed to this middleware through @ControllerUse()
or @ActionUse()
1@Middleware() 2export default class AuthMiddleware extends BaseMiddleware { 3 async middleware(@Request() request, @MiddlewareOptions() options) { 4 if (options.sometimes && Math.random() > 0.5) { 5 if (!request['user']) throw createHttpError(StatusCodes.UNAUTHORIZED) 6 } 7 } 8}
In order to apply middleware to the whole app globally, you need to prefix your middleware files with .middleware
.
Recommended structure:
- src
|_ middleware
|_ TopLevel.middleware.js|ts
|_ top.middleware.js|ts
|_ controllers
Some times you require express to handle an specific path in a specific way, for this when declaring global middleware class you can set a pth for it to be applied. For example when you do not care about the http verb just the params.
1@Middleware('/weg')v 2export default class WegMiddleware extends BaseMiddleware { 3 async middleware() { 4 this.status('OK').send('Thanks for visiting the web') 5 } 6}
strategy
'global' | 'each'
default: global
By default global middleware is applied to the express app as any other middleware like cors
or helmet
but you can configure your global middleware to run individually alongside each action by setting the strategy
option to each
. Then the middleware will run just after the body parser is applied and before the controller an action middleware.
1@Middleware({ strategy: 'each' }) 2export default class AuthMiddleware extends BaseMiddleware { 3 async middleware(@Request() request) { 4 if (options.sometimes && Math.random() > 0.5) { 5 if (!request['user']) throw createHttpError(StatusCodes.UNAUTHORIZED) 6 } 7 } 8}
You can use middleware as a pure RequestHandler
function in both top level middleware and middleware passed through @ControllerUse()
or @ActionUse()
.
1export default function middleware(request, response, next) { 2 request.context = {} 3 next() 4}
Global middleware as function will always run globally and can not be configured to run alongside actions.
ExpressControllers
will emit events regarding request being processed.
1expressControllers.on('request:start', (event) => console.log(event)) 2expressControllers.on('request:not-found', (event) => console.log(event)) 3expressControllers.on('request:error', (event) => console.log(event)) 4expressControllers.on('request:middleware', (event) => console.log(event)) 5expressControllers.on('request:handler', (event) => console.log(event)) 6expressControllers.on('request:end', (event) => console.log(event)) 7expressControllers.on('warning', (event) => console.log(event))
This library is developed in TypeScript and shipped fully typed.
The development of this library happens in the open on GitHub, and we are grateful to the community for contributing bugfixes and improvements. Read below to learn how you can take part in improving this library.
No vulnerabilities found.
No security vulnerabilities found.