new-koa-router
TypeScript icon, indicating that this package has built-in type declarations

1.0.15 • Public • Published

new-koa-router

Router for Koa.js

NPM version NPM Downloads

Installation

Install using npm:

npm install new-koa-router

Contributing

Please submit all issues and pull requests to the new-koa-router repository!

Tests

Run tests using npm test

Support

If you have any problem or suggestion please open an issue here.

Example

Simple

import Koa from "koa";
import Router from "new-koa-router";
 
const app = new Koa();
const router = new Router();
 
router
    .get("/users/:type/:id", (ctx) => ctx.body = ctx.params)
    .get("/posts", (ctx) => ctx.body = "GET /posts")
    .post("/users", (ctx) => ctx.body = "POST /users")
    .post("/posts", (ctx) => ctx.body = "POST /posts");
 
app.use(router.routes());
app.listen(3000);

Middleware

const Middleware = (ctx, next) => {
    ctx.user  = {
        id: 1,
        username: "rs-hub",
    };
    return next();
};
 
router
    .get("/users", middleware, (ctx) => ctx.body = ctx.user)
    .get("/users/:type/:id", (ctx) => ctx.body = ctx.params)
    .get("/posts", (ctx) => ctx.body = "GET /posts")
    .post("/users", (ctx) => ctx.body = "POST /users")
    .post("/posts", (ctx) => ctx.body = "POST /posts");

Use

import Koa from "koa";
import Router from "new-koa-router";
import koaJwt from 'koa-jwt';
import * as jwt from 'jsonwebtoken';
import * as bluebird from 'bluebird';
 
const app = new Koa();
const routerPrivate = new Router();
 
routerPrivate.use(koaJwt({ secret: 'key' }));
routerPrivate
    .get('/jwt', (ctx) => {
        ctx.body = ctx.state.user;
    });
 
app.use(routerPrivate.routes());
app.listen(3000);

Redirect

router.redirect('/source', '/destination');

or

router.get("/source", (ctx) => {
    ctx.status = 301;
    ctx.redirect('/destination');
});

Prefix

const router = new Router({ prefix: "/users" });
 
router.get("/", (ctx) => {});
router.post("/:id", (ctx) => {});

Package Sidebar

Install

npm i new-koa-router

Weekly Downloads

2

Version

1.0.15

License

ISC

Unpacked Size

13 kB

Total Files

14

Last publish

Collaborators

  • rs-hub