npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

express-controller-decorator

v1.5.0

Published

Controller decorator to easily bind mvc to an express app

Downloads

36

Readme

: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