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

@anfo/koa-decorators

v1.0.2

Published

- route - param - query - loginCheck - 基于`stage-1`的decorator,使用`@babel/plugin-proposal-decorators`插件时需要设置`{"legacy": true}`

Downloads

6

Readme

feature

  • route
  • param
  • query
  • loginCheck
  • 基于stage-1的decorator,使用@babel/plugin-proposal-decorators插件时需要设置{"legacy": true}

Install

npm i koa-serve-decorator

API

@route(path: string, method?: string)

声明一个路由,可以装饰到类/方法上,可以在routeAll时提供base: String来设置baseURL

@param(param: Object)

声明body参数的校验规则,如果不满足会抛出异常,会对ctx.request.bodyctx.params的内容进行校验,不能出现相同的变量名,因为是合在一起校验的

@query(param: Object)

声明query参数的校验规则,如果不满足会抛出异常

参数校验依赖于 validator-biang

@loginCheck

声明是否需要检查用户是否登录,依赖jsonwebtoken,使用时需要在routeAll时提供jwtSecret: String, getToken: Function两个值

解密的登陆数据会放在ctx.request.user

@service

装饰一个类,会在类中注入ctx成员,同时创建一个该类的对象挂载在ctx中,且不同的service之间可以互相调用。

@beforeRoute

装饰service的类成员函数,此service的成员函数会在每次用户请求时被调用

@afterRoute

装饰service的类成员函数,此service的成员函数会在每次用户请求后被调用

routeAll(options: Object)

因为@loginCheck, @route, @param, @query之间在实现的层面存在顺序问题,所以他们的初始化都使用同一个routeAll函数,当然,使用的顺序是不会影响结果的serviceAll应该在routeAll前被注册

  • options
    • jwtSecret: string 提供jsonwebtoken库所需要的jwtSecret
    • getToken: Function 提供@loginCheck所需要的token来源。
    • base: [0: path, 1?: method] 提供所有@route标记的控制器的根路径
      • e.g. base: ['/api', 'all']
      • e.g. 只设置method base: ['/', 'all']
      • e.g. 只设置path base: ['/']

serviceAll()

初始化所有的@service,实现service标记的功能,serviceAll应该在routeAll前被注册

initAll(options: Object)

初始化全部decorators,会顺序调用serviceAllrouteAll

  • options: Object
    • route: Object routeAll的参数
    • dirs: [[string]] 指定该参数可以自动include所有的路由类和Service类,基于require-all
      • e.g. 后面recursive部分的其它配置参考require-all的配置
        initAll({
            dirs: [
                [`${__dirname}/controller`, {recursive: true}],
                //...
            ]
        })
      • 当前默认的配置是 filter: /.js$/
    • service还没有相关参数,所以位置如此预留了

const Koa = require('koa');
const {route, param, query, loginCheck, service, initAll} = require('koa-serve-decorator');

@route('/post', 'get')
class A{

    @route('/:id')
    //id必须存在,同时为非空字符串
    //详细规则参考 https://github.com/longjiahui/validator-biang
    @param({
        id: 'truthyString'
    })
    async a(ctx, next){
        //路由是 get /post/:id
    }

    @loginCheck
    @query({
        content: 'truthyString',
        title: 'truthyString',
    })
    @route('/save', 'put')
    async b(ctx, next){
        //路由是 put /post/save
        //这里可以访问service
        ctx.bService;
        ctx.aService;
    }
}

@service
class AService{
    a(){
        console.log('a');
        //service可以访问service 或者ctx的其它内容
        this.ctx.bService.b();
    }
}
@service
class BService{
    b(){
        console.log('b');
    }
}

let app = new Koa();
app.use(initAll({
    route:{
        // 设置baseURL 则@route监听的路由都会设置在/api下
        base: ['/api', 'post'],
        // 设置loginCheck所需要的参数
        jwtSecret: 'secret',
        getToken: ctx=>ctx.headers.authorization,
    }
}));
app.listen(3000);

错误捕获

已经错误会以错误码提供,详细信息参考err.msg字段

//一个middleware
const {errno} = require('koa-serve-decorator');

module.exports = async (ctx, next)=>{
    try{
        await next();
    }catch(err){
        if(err.code === errno.ERR_ARG){
            //参数校验错误
            console.log(err.msg);
        }
}

错误码 errno

  • ERR_ARG 参数错误
  • ERR_NOTOKEN loginCheck时没获得token
  • ERR_VERIFY_ERROR loginCheck校验失败
  • ERR_GETTOKEN_ERROR 获取token失败,
  • ERR_GETJWTSECRET_ERROR 获取jwtScret失败