1.0.15 • Published 5 years ago

new-koa-router v1.0.15

Weekly downloads
1
License
ISC
Repository
github
Last release
5 years ago

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) => {});
1.0.15

5 years ago

1.0.14

5 years ago

1.0.13

5 years ago

1.0.12

5 years ago

1.0.11

5 years ago

1.0.10

5 years ago

1.0.9

5 years ago

1.0.8

5 years ago

1.0.7

5 years ago

1.0.6

5 years ago

1.0.5

5 years ago

1.0.4

5 years ago

1.0.3

5 years ago

1.0.2

5 years ago

1.0.1

5 years ago

1.0.0

5 years ago