Skip to content

rs-hub/new-koa-router

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

28 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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

About

Router for Koa.js.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published