1.0.0-preview.1 • Published 5 years ago

koa-router-middleware v1.0.0-preview.1

Weekly downloads
1,318
License
MIT
Repository
github
Last release
5 years ago

koa-router-middleware

A router middleware for koa.

Installation

yarn

Usage

./index.js

import * as Koa from "koa";
import api from "./routes/api";

new Koa().use("/api", api).listen(() => {
  console.log("server started");
});

./routes/api.js

import Router from "koa-router-middleware";

export default new Router()
  .use(ctx => {
    ctx.state.user = { name: "James" };
  })
  .get("/cat", ctx => {
    ctx.status = 200;
    ctx.body = [{ type: "bengal" }, { type: "bombay" }];
  })
  .get("/cat/:id", ctx => {
    ctx.status = 200;
    ctx.body = { type: "bengal" };
  })
  .post("/cat", ctx => {
    ctx.status = 201;
    ctx.body = { type: "siamese" };
  })
  .put("/cat/:id", ctx => {
    ctx.status = 200;
    ctx.body = { type: "siamese" };
  })
  .delete("/cat/:id", ctx => {
    ctx.status = 200;
  });