Giter Site home page Giter Site logo

express-decorators's Introduction

express-decorators

NOTE: this has been rewritten for version 1, with some breaking changes

Provides decorators for easily wiring up controller classes to express.js routes. If you you use hapijs and want something similar, then the hapi-decorators project has you covered.

TypeScript definitions are built in.

Installation

$ npm install --save express-decorators

Example

import * as web from 'express-decorators';
import myMiddlewareFunction from './middleware';
import express from 'express';

/*** define a controller class ***/

@web.basePath('/hello')
public class TestController {
  constructor(target) {
    this.target = target;
  }

  @web.get('/world', myMiddlewareFunction)
  async sayHelloAction(request, response) {
    response.send(`hello, ${this.target}`);
  }

  @web.use()
  async otherMiddleware(request, response, next) {
    // this will get called for every action
  }
}

/*** install the routes in an express app ***/
let app = express();
let test = new TestController('world');
web.register(app, test);

/*** now we can go to  /hello/world and get 'hello, world' back! ***/

Notes

  • actions are called with the correct context (i.e. this is an instance of the class)
  • actions can return promises (or be async methods) and errors will get handled properly

API

basePath(path: string)

Class decorator to add a base path to every route defined in the class.

middleware(fn: Middleware)

If fn is a function, then the function is added as route-specific middleware for the action. Note that the middleware will be bound to the controller instance.

If fn is a string, then the method with that name will be exectued as route-specific middleware when the action is invoked.

route(method: string, path: string, middleware: Middleware[])

Marks the method as a handler for the specified path and http method. The route parameter is just passed straight to the relevant express method, so whatever is valid there is valid here.

There are shortcuts for the methods below. I.e., instead of route('get', '/') you can use get('/').

  • all
  • delete (called del so it compiles)
  • get
  • options
  • param
  • patch
  • post
  • put
  • use

getRoutes(target: Object): Route[]

Gets the route metadata for the target object. Paths are automatically prefixed with a base path if one was defined.

register(router: Express.Router, target: Object)

Registers the routes found on the target object with an express Router instance.

Questions, comments?

Please feel free to start an issue or offer a pull request.

express-decorators's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

express-decorators's Issues

Multiple middleware needs to be specified in an unconventional order

Given the following code:

@web.get('/')
@web.middleware(a)
@web.middleware(b)
@web.middleware(c)
indexAction(req, res, next) { /* <…> */ }

Middlewares will be executed in such order: c → b → a. Which is not what you'd expect.

As a quick workaround, I changed the order in which I attach middlewares, but I guess it's something that could be addressed at library level.

TypeScript definitions?

Hi, typescript newbie here.
I'm trying to use the module in my nodejs+expressjs+typescript backend app and it seems I need to install the reference via tsd install to make it work. Right? Or am I missing something?
Because when I compile my project, I get this

app/app.ts(8,23): error TS2307: Cannot find module 'express-decorators/load'.

I fully understand this is a ES6 module, but it seems really useful for my case too.

Thanks in advance!

HapiJS

I'd love to see something similar for HapiJS!

Would you mind if I created a library based off this one, but for HapiJS? Or if you are planning to, I'd be willing to contribute/test.

How to add middleware for all controller actions?

We have a middleware to be shared among multiple controllers. We also want the middleware being called in every action.

@web.use requires a member function as the middleware, which is not suitable.
@web.middleware assigns middleware to a single action, which is not suitable as well.

Cannot handle errors

an error handling middleware should be able to handle exceptions in the action, for example:

app.use((err, req, res, next) => {
  // ....
});

However when using this module I only got:

Error: .....
    at Handler.<anonymous> (....)
    at ....../node_modules/express-decorators/index.js:45:38

Usage with Babel?

I am not using TypeScript and would still like to use these decorators. Are they also functional when using Babel?

Thanks!

Custom decorator.

Hello. Could you add an instruction to create a custom decorator? What issues I get: the context of the controller class is lost. Could you describe how do you use Reflect Metadata?

Regards.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.