1.0.3 • Published 8 years ago

decorouter v1.0.3

Weekly downloads
4
License
MIT
Repository
github
Last release
8 years ago

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());