Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@mbraun/koa-decorators

Package Overview
Dependencies
Maintainers
1
Versions
4
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@mbraun/koa-decorators

Package for managing multiple routes on koa with a controller-structure

  • 0.0.4
  • latest
  • Source
  • npm
  • Socket score

Version published
Maintainers
1
Created
Source

koa-decorators

npm_version license stability pipeline status coverage report

This package consists of decorator-functions that could be used with koajs.

They are inspired by the .NET WebApi attributes and should add routing information to a controller-class.

Setup

To use this package you have to add support for stage-2 decorators to your preferred compiler.

When used with babeljs, use the @babel/plugin-proposal-decorators plugin without legacy: true.

Getting Started

It is easy to create a controller with routes to an existing koajs-project:

Create Controller

You have to create a Controller class first and add the decorators to it.

import { Route, HttpGet } from '@mbraun/koa-decorators';

@Route('/examples')
class ExampleController {
    @HttpGet('/')
    static GetExamples(ctx) {
        ctx.body = 'Hello World';
        ctx.status = 200;

        return ctx;
    }
}

Add Controller to Koa-Router

Then you have to connect it to a koa-router using the createRoutes function of the koa-decorators package.

import Koa from 'koa';
import Router from 'koa-router';
import { createRoutes } from '@mbraun/koa-decorators';

const app = new Koa();
const router = new Router();

createRoutes(router, ExampleController);

app
  .use(router.routes())
  .use(router.allowedMethods());

Decorators

This package consists of the following decorators:

Nameclassmethod
Routexx
AcceptVerbsx
Http<Verb>x
Middlewarexx

Route

The Route-decorator could be used on class-level and method-level. It is possible to set multiple Routes on the same element.

On class-level the decorator works as a prefix for each route that is specified inside this class.

On method-level it has to be used with a AcceptVerbs or Http<Verb>-decorator.

import { AcceptVerbs, Route } from '@mbraun/koa-decorators';

@Route('/examples')
class ExampleController {
    @Route('/:id')
    static GetExampleById(ctx) {
        ctx.body = `Hello ${ctx.params.id}`;
        ctx.status = 200;

        return ctx;
    }
}

AcceptVerbs

The AcceptVerbs-decorator could only be used on method-level. It specifies the possible http-methods that could be handled by the route.

import { AcceptVerbs } from '@mbraun/koa-decorators';

class ExampleController {
    @AcceptVerbs('GET', 'POST')
    static GetExampleById(ctx) {
        ctx.body = `Hello World!`;
        ctx.status = 200;

        return ctx;
    }
}

Http<Verb>

Because most routes only work with one http-method and one route this library contains shortcut-decorators too.

shortcut-decorators where created for the following http-methods:

  • GET
  • POST
  • PUT
  • PATCH
  • DELETE
import { HttpGet } from '@mbraun/koa-decorators';

class ExampleController {
    @HttpGet('/')
    static GetExampleById(ctx) {
        ctx.body = `Hello World!`;
        ctx.status = 200;

        return ctx;
    }
}

Middleware

The middleware-decorator could be used on class-level and method-level.

It should be compatible with any existing middleware for koa.

On class-level, the middleware is used on any route inside this class. On method-level, the middleware is only used on all routes that are mapped to this method.

import { Middleware } from '@mbraun/koa-decorators';

async function RequestTimeLogger(ctx, next) {
  const start = Date.now();
  await next();
  const ms = Date.now() - start;
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
}

class ExampleController {
    @Middleware(RequestTimeLogger)
    static GetExampleById(ctx) {
        // ...
    }
}

It is also possible to add multiple middlewares using only one Middleware-decorator:

import { Middleware } from '@mbraun/koa-decorators';

class ExampleController {
    @Middleware(Middleware1, Middleware2)
    static GetExampleById(ctx) {
        // ...
    }
}

decorateMiddleware

The decorateMiddleware function creates a Middleware-Decorator with a given middleware. It could be used on a custom middleware that is required on multiple routes across multiple controllers. It should make things a lot more easier:

Middleware.js

import { decorateMiddleware } from '@mbraun/koa-decorators';

async function RequestTimeLogger(ctx, next) {
  const start = Date.now();
  await next();
  const ms = Date.now() - start;
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
}

export default decorateMiddleware(RequestTimeLogger);

Controller.js

import RequestTimeLogger from './Middleware.js';

class ExampleController {
    @RequestTimeLogger
    static GetExampleById(ctx) {
        // ...
    }
}

Keywords

FAQs

Package last updated on 23 Mar 2019

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc