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

@edcarroll/koa-router-decorators

v1.0.0

Published

Convenience decorators for koa-router

Downloads

6

Readme

Koa Router Decorators

Convenience decorators for koa-router. Adds concept of controller classes, with route methods on the class.

Installation

$ npm install --save @edcarroll/koa-router-decorators

Quickstart

Import the necessary decorators and the useController helper function from the library:

import * as Koa from "koa";
import * as KoaRouter from "koa-router";
import {Controller, Get, IMiddleware, useController} from "@edcarroll/koa-router-decorators";

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

Create your first controller:

@Controller('/')
class RootController {
    @Get('/')
    public helloWorld:IMiddleware[] = [
        async ctx => {
            ctx.body = "hello, world!";
        }];
}

Connect the controller to the root router and you're good to go!

useController(router, new RootController());

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

app.listen(20000);

Decorators

@Controller(pathPrefix:string, ...middleware?:IMiddleware[])

Marks class as router controller. To make use of the controller either connect it directly to a KoaRouter instance with useController or nest it within an existing controller using @NestedController.

Routes are defined on the controller itself, as properties, decorated with @Route or its equivalent convenience decorators. The pathPrefix property is used to prefix each route within the controller's path with a specified string. The middleware property is a spread array of middleware that when set are applied to all of the child routes of the controller and its nested controllers.

Path Prefix Usage

@Controller('/demo')
class DemoController {
    @Get('/')
    public demo:IMiddleware[] = [async ctx => ctx.body = "demo"];
}

// GET /demo/ : 200 : "demo"

Middleware Usage

import {Controller, Get, Post} from "@edcarroll/koa-router-decorators";
import {loggingMiddleware, authMiddleware} from "...";

@Controller('/demo', loggingMiddleware, authMiddleware)
class DemoController {
    @Get('/')
    public demo:IMiddleware[] = [async ctx => ctx.body = "demo"];

    @Post('/')
    public example:IMiddleware[] = [async ctx => ctx.body = "example"];
}

// GET  : /demo : 401
// POST : /demo : 401

@NestedController()

Nested controllers are how complex controllers can be built up from a single root controller. When you have defined your 'sub-controller' class and decorated it with @Controller, place an of it instance within the parent controller with the @NestedController decorator.

Usage

import {Controller, NestedController, Get} from "@edcarroll/koa-router-decorators";

@Controller('/nested')
class SubController {
    @Get('/route')
    public nested:IMiddleware[] = [async ctx => ctx.body = "nested"];
}

@Controller('/demo')
class DemoController {
    @NestedController()
    public nestedController = new SubController();
}

// GET : /demo/nested/route : 200 : "nested"

@Route(method:RequestMethod, path:string)

Defines a route on the controller. To set up a route, use this to decorate an array of IMiddleware. The array of middleware will be attached to the controller, using the provided method and path, and are executed in order.

Route parameters work as expected, e.g. /people/:id will set ctx.params.id.

Usage

import {Controller, Route, RequestMethod} from "@edcarroll/koa-router-decorators";

@Controller('/')
class RootController {
    @Route(RequestMethod.Get, '/example')
    public exampleRoute:IMiddleware[] = [
        async (ctx, next) => {
            // 1. This middleware is called first
            ctx.status == 204; // false

            await next(); // 2. We then await downstream

            // 4. Control flows back upstream
            ctx.status == 204; // true
        },
        async ctx => {
            ctx.status = 204; // 3. This middleware is called, changing the status then returning
        }];
}

// GET : /example : 204

@Get(path:string), @Put(...), @Post(...)...

These are convenience decorators, and are each shorthand for @Route(RequestMethod.[Get|Put|Post|...], path)

Usage

@Controller('/')
class DemoController {
    @Get('/example')
    @Post('/example')
    public example:IMiddleware[] = [async ctx => ctx.body = "hello, world!"];
}

API

useController(router:KoaRouter, controller:any):void

Helper function that connects a controller to a KoaRouter instance. Usually you will only call this function once, when your application starts up.

Usage

import * as KoaRouter from "koa-router";
import {Controller} from "@edcarroll/koa-router-decorators";

const router = new KoaRouter();

@Controller('/')
class RootController {}

useController(router, new RootController());

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