Git Product home page Git Product logo

koa-router-decorators's Introduction

koa-router-decors

简化koa-router路由书写方法。

使用方法

1. 书写路由文件user.ts;

import { get, put, post, del, patch } from 'koa-router-decors';
class User {
    @get('/user')
    async get(ctx) {
        ctx.body = {
            user: {},
        };
    }
}

2. 加载路由文件

import * as Koa from 'koa';
import { load } from 'koa-router-decors';

const app = new Koa();
app.use(load('/api', 'router_path').routes());
app.listen(9100);

3. 特殊用法

3.1 特殊的路由写法

// 给User类上所有路由添加中间件
@middlewares([setResponseTime])
class User {
    // 一个方法可以生成多个路由;针对特定路由,可以修改前缀,也可以添加中间件
    @get('/method')
    @get('/method', { prefix: '', middlewares: [] })
    async get(ctx: Koa.Context) {
        ctx.body = {
            method: ctx.method,
        };
    }
}

async function setResponseTime(ctx, next) {
    let date = new Date();
    await next();
    ctx.set('X-Response-Time', String(new Date().getTime() - date.getTime()));
}

3.1 特殊的路由加载

const app = new Koa();
// 可以多次调用`load`分别加载不同的目录
app.use(load('/api', `${__dirname}/router/api`).routes());
app.use(load('/web', `${__dirname}/router/web`).routes());
export default app.listen(9100);

koa-router-decorators's People

Contributors

lichangwei avatar licvvei avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.