npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@zkboys/egg-route-decorator

v1.0.2

Published

Define egg.js router and middleware use decorator

Downloads

3

Readme

@zkboys/egg-route-decorator

NPM version Test coverage Known Vulnerabilities npm download

使用装饰器来定义 egg.js 的路由、中间件、校验、swagger文档等

开启插件

// config/plugin.js
exports.routeDecorator = {
    enable: true,
    package: '@zkboys/egg-route-decorator'
}

基于 typescript 的 eggjs 项目可直接使用装饰器
如果是 js 项目,则需要手动安装 babel-plugin-transform-decorators-legacybabel-plugin-transform-object-rest-spread这两个包,并在项目里加入 .babelrc 文件

.babelrc 定义如下:

{
  "plugins": [
    "transform-decorators-legacy",
    "transform-object-rest-spread"
  ]
}

插件配置

exports.routeDecorator = {
    prefix: '/api',             // 全局统一前缀
    defaultMethod: 'get',       // 默认请求方法
    // wrapperResult: false,    // 是否包装结果
    wrapperResult: {            // 如下配置是默认值
        success(data, ctx) {
            // 函数有返回值,进行包装,如果没有返回值,不包装
            if (data !== undefined) {
                ctx.body = {
                    code: 10,
                    data,
                };
            }
        },
        error(error, ctx) {
            // 对错误信息进行包装
            ctx.body = {
                code: 19999,
                error,
                message: error && error.message,
            };
        },
    },
}

API

| 装饰器 | 级别 | 参数 | 说明 | |----------------------------------------------|----------------|--------------------------------------------------------|-------------------------------------------------------------------------------------| | route(prefix?) | class | prefix:所有当前类路由的统一前缀,默认空 | 当前controller类启用装饰器路由 | | middleware(middleware, index) | class 或 method | middleware:中间件函数;index:中间件顺序 | class级别给所有的方法添加中间件,method级别给当前方法添加中间件 | | get(path, name)、post、put、del、patch、all | method | path:路由地址;name:路由名称 | 给方法添加具体http方法的装饰器 | | header、param、path、query、body | class 或 method | options:校验规则:{name: {required: true, message: '姓名必填'}} | 检验中间件,需要项目使用 egg-validator-async插件,规则参考:https://github.com/yiminghe/async-validator | | deprecated、description、response、summary、tags | class 或 method | swagger相关 | swagger相关 |

使用场景

  • 不用单独定义 router,直接在 controller 里通过装饰器自动生成 router
  • 支持在 controller 里通过装饰器方式加入中间件,类级别以及方法级别

示例

import { Controller } from 'egg';
import {
    route,
    all,
    get,
    post,
    put,
    patch,
    del,
    middleware
} from '@zkboys/egg-route-decorator'

const mi = name => (_ctx, next) => {
    console.log('passed  middleware ' + name);
    next();
};

// controller类上启用装饰器路由

// root path is '/'
@route()

// root path is '/'
@route('/')

// root path is '/routename'
@route('/routename')

// root path is '/routename/action'
@route('/routename/action')

// 支持定义参数
@route('/routename/:name')
@middleware(mi('RoleController'))
export default class RoleController extends Controller {
    // sub-path is '/index'
    public async index() {
        // this.ctx.body = '123';
        return {
            name: 'role 张三',
            age: 24,
        };
    }

    // sub-path is '/'
    @get()

    // sub-path is '/'
    @get('/')

    // sub-path is '/roles'
    @get('/roles')

    // sub-path is '/roles/:id'
    @get('/roles/:id')
    public async getRoles() {

        return {
            name: 123,
        }
    }

    // 没有使用装饰器,默认生成路由:/roles
    @middleware(mi('roles'))
    public async roles() {
        throw Error('测试错误 role');
    }
}

response 支持的写法

export default class UserController extends Controller {
    @response(Boolean) // Number String
    @response(userModel.responseModel)
    @response({ description: 'ok', schema: userModel.responseModel })
    @response([userModel.responseModel])
    @response('操作成功,返回true') // { description: '操作成功,返回true', schema: null }
    @response({
        count: { name: '总条数', type: 'number' },
        rows: {
            name: '当前页记录',
            type: 'array',
            items: {
                type: 'object',
                properties: userModel.responseModel,
            },
        },
    })
    async index() {
        // ...
    }
}

License

MIT