Giter Site home page Giter Site logo

swimlane / trafficlight Goto Github PK

View Code? Open in Web Editor NEW
74.0 36.0 11.0 619 KB

๐Ÿšฆ Flexible NodeJS Routing Decorators for API Routing

License: MIT License

TypeScript 99.69% JavaScript 0.31%
koa typescript es7 es7-decorators nodejs decorators express koa2 routing

trafficlight's Introduction

Trafficlight ๐Ÿšฆ

Codacy Badge Codacy Badge Build Status npm version

A flexible NodeJS Routing Decorators for API Routing. Features include:

  • Built for KOA2
  • Bring-your-own router
  • Bring-your-own body parser
  • TypeScript and ES7 Support
  • DI compatible

Usage

Building

npm run build

Install

npm i trafficlight --S

Note: You must have reflect-metadata installed as a peer dependency

Setup KOA

import 'reflect-metadata'; /* Must be singleton */
import * as Koa from 'koa';
import * as Router from 'koa-router';
import * as body from 'koa-better-body';

import { ProfileController } from './controllers';
import { bindRoutes } from 'trafficlight';

export function setupKoa() {
  const app = new Koa();

  app.use(body());
  buildRoutes(app);
  app.listen(3000);

  return app;
}

function buildRoutes(app) {
  const routerRoutes = new Router();

  // any router can be used, we support koa-router out of the box
  bindRoutes(routerRoutes, [ProfileController]);

  // if you are using with some sort of DI system you can pass
  // a third parameter callback to get the instance vs new ctrl.
  // bindRoutes(routerRoutes, [ProfileController], (ctrl) => injector.get(ctrl));

  app.use(routerRoutes.routes());
  app.use(routerRoutes.allowedMethods());
}

Decorate the controller

import { Controller, Get, Use, Param, Body, Delete, Put, Post, QueryParam } from 'trafficlight';

@Controller('/profile')
@Use(someMiddleware)
export class ProfileController {

  @Get()
  getAll(@QueryParam('filter') filter) {
    // return []
  }

  @Get('/:id')
  @Use(someMiddleware)
  getOne(@Param('id') id) {
    // return {}
  }

  @Post()
  create(@Body() body) {
    // return {}
  }

  @Post('/:id/upload')
  upload(@Param('id') id, @File() file) {
    // return {}
  }

  @Put('/:id')
  update(@Param('id') id, @Body() body) {
    // return {}
  }

  @Delete('/:id')
  destroy(@Param('id') id) {
    // return success
  }

}

API

  • bindRoutes(routerTable, controllers, getter) - Binds the controller to the route table.
  • Controller(url?) - Top level controller decorator. Optional root url
  • Route(method, url?) - Abstract method decorator, accepts method type, url
  • Get(url?) - Http GET method, accepts URL
  • Post(url?) - Http Post method, accepts URL
  • Put(url?) - Http Put method, accepts URL
  • Delete(url?) - Http Delete method, accepts URL
  • Params() - Returns all the parameters passed in the request
  • Param(val) - Returns a specific parameter passed in the request
  • File() - Returns a single file in the request body
  • Files() - Returns all files in the request body
  • QueryParams() - Returns all the query parameters passed in the request url as an object
  • QueryParam(val) - Returns a specific query parameter passed in the request url
  • Ctx() - Returns the KOA context object
  • Req() - Returns the Node request object
  • Request() - Returns the KOA request object
  • Res() - Returns the Node response object
  • Response() - Returns the KOA response object
  • Body() - Returns the request body object
  • Fields() - Returns the request fields object
  • Use() - Middleware decorator for class and functions

Special return types

Since typescript doesn't allow decorators on return types. Certain type has been added to indicate and allow for file download.

  • FileDownload: {fileName: string, mimeType: string, stream: ReadStream}

Inspiration

Credits

trafficlight is a Swimlane open-source project; we believe in giving back to the open-source community by sharing some of the projects we build for our application. Swimlane is an automated cyber security operations and incident response platform that enables cyber security teams to leverage threat intelligence, speed up incident response and automate security operations.

trafficlight's People

Contributors

amcdnl avatar brantw avatar dmikov avatar hypercubed avatar qingwei-li avatar shaunburdick avatar spiritree avatar xetatronics avatar

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  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  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

trafficlight's Issues

Need more explanation

I'm not clear with the following snippet.

// if you are using with some sort of DI system you can pass
// a third parameter callback to get the instance vs new ctrl.
// bindRoutes(routerRoutes, [ProfileController], (ctrl) => injector.get(ctrl));

Is there a better example?

QueryParam with types like number/boolean are string

QueryParam's are not resolving to their types. Given the following:

@Post('/run/:id')
async run(@QueryParam('async') isAsync: boolean = true): Promise<any> {
}

The property isAsync would resolve to "false" rather than false boolean.

Add InjectAsync to allow custom parameter decorators which are async

I have some custom decorators to validate my parameters. Currently, i can create them with Inject(), and that works fine. However, i would like to use promises inside my decorators but trafficlight is not waiting for the execution.

My proposal is to add InjectAsync(). I can do this and would like to push a PR, but first i want to be sure someone is here to approve my request. Please let me know!

Other than that - Thanks for this package, i use it because no similar package can deal with custom routers.

Add ability to response with Http Code

Add the ability to response with an object that defines a response code

import { Controller, Get, Ctx } from 'trafficlight';

class MyController {

  @Get('/foo')
  foo(@Ctx() ctx): string {
    ctx.set('Location', '/bar');
    ctx.status = 301;
    return 'Moved to /bar';
  }

  @Get('/bar')
  bar(): boolean {
    return true;
  }
}

** becomes **

import { Controller, Get, HttpCodeResponse } from 'trafficlight';

@Controller()
class MyController {

  @Get('/foo')
  foo(): HttpCodeResponse {
    return HttpCodeResponse(301, { Location: '/bar' }, 'Moved to /bar');
  }

  @Get('/bar')
  bar(): boolean {
    return true;
  }
}

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.