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

@java_swing/egg-class-validator

v0.1.5

Published

class-validator plugin for Egg.js

Downloads

4

Readme

egg-class-validator

NPM version npm download

基于 class-validator 提供数据校验方法。

开启插件

// config/plugin.js
exports.classValidator = {
  enable: true,
  package: '@hackycy/egg-class-validator',
};

定义验证类

import { Expose } from 'class-transformer';
import {
    Contains,
    IsInt,
    Length,
    IsEmail,
    IsFQDN,
    IsDate,
    Min,
    Max,
  } from 'class-validator';

export class Post {
    @Expose()
    @Length(10, 20)
    title: string;

    @Expose()
    @Contains('hello')
    text: string;

    @Expose()
    @IsInt()
    @Min(0)
    @Max(10)
    rating: number;

    @Expose()
    @IsEmail()
    email: string;

    @Expose()
    @IsFQDN()
    site: string;

    @Expose()
    @IsDate()
    createDate: Date;
  }

验证

import { Controller } from 'egg';
import { Id } from '../dto/id';
import { Post } from '../dto/post';

export default class HomeController extends Controller {
  public async index() {
    const { ctx } = this;
    ctx.body = await ctx.service.test.sayHi('egg');
  }

  public async test() {
    const { ctx } = this;
    // 会获得具体的类型
    const p = await ctx.validate<Post>(Post);
    this.ctx.logger.info(p);
    ctx.body = p;
  }

  public async testg() {
    const { ctx } = this;
    const dto = await ctx.validate(Id, ctx.request.query);
    this.ctx.logger.info(dto);
    ctx.body = 'success';
  }
}

ctx.validate会将传入的校验数据对象转换成Type指定的类型,指定范型可以更友好的使用类型。

已经在Application对象上挂载了validator属性,即class-validator的Validator。可以在该属性扩展更多schema等。

更多操作可以查看官方的文档

转换对象使用了class-transformer,可以在config中配置

import { EggAppConfig, EggAppInfo, PowerPartial } from 'egg';

export default (appInfo: EggAppInfo) => {
  const config = {} as PowerPartial<EggAppConfig>;

  // 配置 class-transformer options
  config.classValidator = {
    classTransformOptions: {
      excludeExtraneousValues: false
    },
    // 自定义错误处理
    handleError: (ctx, _errors) => {
      // 做你想做的事情,第一个参数为Context,第二个参数为ValidationError[]
      ctx.throw(400, '参数异常');
    }
  }

  // the return config will combines to EggAppConfig
  return {
    ...config,
    ...bizConfig,
  };
};

获取Query值为String类型问题

在处理Get的请求中获取的query参数都是String类型,那么定义Dto的时候就无法直接使用@IsInt注解,只能使用@IsNumberString来做参数验证。这里提供一个思路来提前将Query的参数转换需要的类型。

DTO定义

import { Expose, Transform } from 'class-transformer';
import {
    IsNumberString,
    IsInt,
  } from 'class-validator';

export class Id {

  @IsNumberString()
  @Expose()
  sid: string;

  @IsInt()
  @Transform(value => { return parseInt(value) }, { toClassOnly: true })
  @Expose()
  id: number;

}

重点是class-transformer@Transform注解。

这里需要理解框架处理的顺序,当使用ctx.validate方法时,

1、首先使用class-transformer将验证的参数转为成转换成Type指定的类型,那么定义的注解就会先执行转换类型。

2、然后再使用class-validator进行参数校验

更多查看example提供示例

有问题或Bug

请提出issues

License

MIT