npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@mbraun/koa-decorators

v0.0.4

Published

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

Downloads

9

Readme

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:

| Name | class | method | | ------------ | ----- | ------ | | Route | x | x | | AcceptVerbs | | x | | Http<Verb> | | x | | Middleware | x | x |

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) {
        // ...
    }
}