decorouter

1.0.3 • Public • Published

Decorouter

Simple decorator based es6 class method routing for express nodejs

NPM version Build Status

Installation

$ npm install decorouter --save

Usage

usage requiring babel-plugin-transform-decorators-legacy with babel 6

import { Route } from '../decorouter';
 
export class Controller
{
    constructor() {
        //usage not requiring babel-plugin-transform-decorators-legacy
        Route('get','/methodWithoutDecorator')(this, 'methodWithoutDecorator');
    }
 
    //additional handlers can be added after route eg (req, res, next) => next()
    @Route('get', '/method')
    method(req, res) {
        res.send({from: 'method'});
    }
 
    //async methods can (and probably should) be used where neccessary
    @Route('get', '/methodAsync')
    async methodAsync(req, res) {
        res.send({from: 'methodAsync'});
    }
 
    //additional handlers can be added after route eg (req, res, next) => next()
    @Route('get', '/methodWithAdditionalHandler', (req, res, next) => { res.handlerCalled = true; next();})
    methodWithAdditionalHandler(req, res) {
        res.send({
            from: 'methodWithAdditionalHandler',
            handlerCalled: res.handlerCalled});
    }
 
    methodWithoutDecorator(req, res) {
        res.send({from: 'methodWithoutDecorator'});
    }
 
    //will defaut to 'get' and '/defaultRouteAssignedByMethodName'
    @Route()
    defaultRouteAssignedByMethodName(req, res) {
       res.send({from: 'defaultRouteAssignedByMethodName'});
    }
 
}

Registering routes

import { addRoutes, addRoutesFromDir } from 'decorouter';
import express from 'express';
import { Controller } from './testControllers';
 
let router = express.Router();
addRoutes(router, () => new Controller());
 
//or all in this directory
addRoutesFromDir(router, module, (typeObject) => new typeObject());

Package Sidebar

Install

npm i decorouter

Weekly Downloads

3

Version

1.0.3

License

MIT

Last publish

Collaborators

  • raudsley-ot
  • vmitrevski