Socket
Socket
Sign inDemoInstall

express-controller-decorator

Package Overview
Dependencies
3
Maintainers
1
Versions
46
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    express-controller-decorator

Controller decorator to easily bind mvc to an express app


Version published
Weekly downloads
5
Maintainers
1
Install size
4.24 MB
Created
Weekly downloads
 

Readme

Source

Express Controller Decorator

Github top language Github language count Repository size License Github issues Github stars

About   |   Features   |   Technologies   |   Requirements   |   Starting   |   License   |   Author


:dart: About

A simple, lightweit npm package to bind your controllers to express

:sparkles: Features

:heavy_check_mark: uses modern TS decorators;
:heavy_check_mark: support of Middleware;
:heavy_check_mark: No need of instantiating your controllers with the new keyword;

:rocket: Technologies

The following tools were used in this project:

:white_check_mark: Requirements

Before starting :checkered_flag:, you need to have express and Typescript v.4.4 or above installed.

:checkered_flag: Installing

# Install it with npm
$ npm i --save express-controller-decorator

# Install it with yarn
$ yarn add express-controller-decorator

# Install it with pnpm
$ pnpm add express-controller-decorator

:arrow_forward: Usage

First of all, add a @Controller decorator to your Controller. Then, add @HTTPMethod decorators to the methods you wish to be invoked for each http method.

NOTE: All methods that are marked with HTTP method decorators must return ControllerResponse or Promise<ControllerResponse> instance.

Request and Response args will be injected automatically

@Controller('/user')
export class SomeController {
	@Post('/:id') // Request and Response args will be injected automatically
	public getUser(req: Request, res: Response): ControllerResponse {
		// ...some code

		return new ControllerResponse(body, status, headers)
	}

	// NOTE: decorator params are optional
	@Post()
	public createUser(req: Request, res: Response): ControllerResponse {
		// ...some code

		// NOTE: All args here are optional
		return new ControllerResponse(null, 200)
	}
}

The following decorators are available:

  • Controller(path: string) - Decorator to mark classes that are controllers
  • Post(path: string = '/', ...middlewares: Middleware[]) - Method decorator
  • Get(path: string = '/', ...middlewares: Middleware[]) - Method decorator
  • Delete(path: string = '/', ...middlewares: Middleware[]) - Method decorator
  • Put(path: string = '/', ...middlewares: Middleware[]) - Method decorator
  • Patch(path: string = '/', ...middlewares: Middleware[]) - Method decorator
  • Head(path: string = '/', ...middlewares: Middleware[]) - Method decorator
  • Fallback(...middlewares: Middleware[]) - Method decorator to mark a fallback method. It will be invoked when no other route/method passes

Then, you need to add your controllers to the express app instance in your main.ts file:

const app = express()

injectControllers(app)
app.listen(3010)

NEW in 1.3: You can create a custom Context class and make this lib use it instead of express' Request and Response classes. To do so, you need to pass your custom Context class to setContextClass function BEFORE calling injectControllers function. Example:

const app = express()

class MyContext {
	// ...some code

	// all arguments are optional
	constructor(req: Request, res: Response, next: NextFunction) {
		// ...some code
	}
}

setContextClass(MyContext)
injectControllers(app)

app.listen(3010)

If you did specify a custom Context class, you MUST use it instead of express' Request and Response types in your controller methods. Example:

@Controller('/user')
export class SomeController {
	// will work if you specified a custom Context class
	@Post('/:id')
	public getUser(ctx: MyContext): ControllerResponse {
		// ...some code

		return new ControllerResponse(body, status, headers)
	}

	// will NOT work if you specified a custom Context class
	@Post('/:id')
	public getUser(req: Request, res: Response): ControllerResponse {
		// ...some code

		return new ControllerResponse(body, status, headers)
	}
}

There's also a Middleware interface. If you wish to create a Middleware and then use it in your decorators, you must create each Middleware as a class implementing this interface. It has only one method: use() that will be invoked while using the route the middleware sits in. Example:

interface Middleware {
	use(
		request: Request,
		response: Response,
		next: NextFunction
	): void | Promise<void>
}

If you wish to add some middlewares to your Controller or to a specific method:

@Controller('/', new Middleware1(), new Middleware2(), ...)

or

@Get('', new Middleware1(), new Middleware2(), ...)

Note! The middlewares you pass are executed before your method. THe must implement the Middleware interface

Example:

class SomeMiddleware implements Middleware {
	use(
		request: Request,
		response: Response,
		next: NextFunction
	): void | Promise<void> {
		// ... some usefull code
	}
}

@Controller('/auth', new SomeMiddleware()) // <-- Passing Middleware in Controller decorator means it will be invoked before EVERY route in this class
class MyController {
	@Get('/', new SomeMiddleware()) // <-- This Middleware will be used only for this route and this method
	public foo(req: Request, res: Response): ControllerResponse {
		// ...some usefull code
	}
}

:white_check_mark: Todo

  • :white_check_mark: Middleware support
  • :white_check_mark: Fallback route
  • Generate swagger file

:memo: License

This project is under license from MIT. For more details, see the LICENSE file

Made with :heart: by sannnekk

 

Back to top

Keywords

FAQs

Last updated on 19 Mar 2024

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc