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

fast-class-validator

v1.0.0

Published

Decorator-based property validation for classes.

Downloads

4

Readme

fast-class-validator

ES6Typescript的时代,我们可以用classdecorator做很多事情。fast-class-validator可以让plain object转换成某个class的实例,并可以通过注解来校验property的规则。


目录

what is fast-class-transform

Javascript 中有两种对象类型:

  • plain(literal) objects
  • class(constructor) objects

plain objectsObject 的实例,有时候我们也管他叫字面量类型。但有时候我们需要将 plain object 作为某个 ES6 的 class 的实例并且期望对某些class property 制定某些规则,那么fast-class-validator 将会非常适合你。 例如:

// es6 class
class Data {
  @IsNegative(-1)
  prop: number;

  @Contains('hello')
  prop1: string;
}
// literal object
const tmp = {
  prop: '-20',
  prop1: 'hello world',
};

// result instanceof Data
const result = json2class(Data, tmp);

Installation

环境支持:

  • nodejs >= 12
  • typescript>=3
npm i fast-class-validator -S

配置 tsconfig.json:

 "experimentalDecorators": true,
 "emitDecoratorMetadata": true,

methods

json2class

json2class 方法将转换一个 plain object 到一个具体 class 实例

import { json2class } from 'fast-class-validator';

class Hotel {
  id: string;

  name: string;

  address: string;

  latitude: string;

  longitude: string;
}

// hotel is instance of Hotel
const hotel = json2class(Hotel, hotelJson);

Annotations

通过json2class将会把一个plain object转换成某个具体class的实例,但仍然会存在一个问题Hotel中定义的property有可能与hotelJson对象属性不同,那么这就会带来一个严重问题,运行时与编码时所对应的数据不一致。 fast-class-validator可以解决这种问题。

通过Schema注解解决plain object中属性类型不匹配的问题

class Hotel {
  @Schema()
  id: string;

  @Schema()
  name: string;

  @Schema()
  address: string;

  @Schema()
  latitude: string;

  @Schema()
  longitude: string;
}

const hotelJson = {
  id: 1,
};
const hotel = json2class(Hotel, hotelJson); //{id:'1'}

Schema 注解并不强制要求 plain object 完全与定义的 class object一致(属性的类型和属性个数),Schema只起到类型转换的作用。如果我们想要class object 必须满足某种规则如下:

// 通过给 Hotel中的property增加规则注解,来让plain object的属性满足对应的规则。

class Hotel {
  @IsUUID()
  id: string;

  @IsString()
  name: string;

  @Schema()
  address: string;

  @IsLatitude()
  latitude: string;

  @IsLongitude()
  longitude: string;
}

const hotelJson = {
  id: 1,
};
const hotel = json2class(Hotel, hotelJson); //PlainToClassError

working with nested object

有时候我们可能需要转换复杂的数据结构(对象的多级嵌套),但是由于目前typescript还不能很好提供reflect能力,所以暂时只支持class

class Room {
  @Required()
  type: string;
}

class Hotel {
  @IsUUID()
  id: string;

  // 通过Schema收集refer的元信息
  @Schema()
  refer: Room;
}

type conversion

类型转换,并不是所有的 plain object 都能转换对应的 class object,只有typescriptjavascript 的交集类型才能满足类型转换

interface ITmp {
  prop5: string;
}
class Hotel {
  @Schema()
  prop1: unknown;

  @Schema()
  prop2: any;

  @Schema()
  prop3: string | number;

  @Schema()
  prop4: ITmp;
}
//ts独有的类型都无法进行转换到对应的类型,fast-class-validator将输出plain object 的数据
const tmp = {
  prop1: '输出原始类型',
  prop2: { prop2: '校验通过' },
  prop3: ['1', '2'],
  prop4: '字符串',
};
const result = json2class(Hotel, tmp);
/**
 * result 为
 * {
  prop1: '输出原始类型',
  prop2: { prop2: '校验通过' },
  prop3: ['1', '2'],
  prop4: '字符串',
}
 * /

support-type

fast-class-validator 支持的类型转换如下

  • class object
  • Object
  • Array
  • Map
  • Set
  • string
  • number
  • boolean
  • Date
  • Promise

Annotations list

common

| 注解 | 描述 | | ------------ | ------------------------------------------ | | @Schema | 收集元信息转换为目标类型 | | @IsOptional | 可选校验,当值为 null,undefined 则忽略校验 | | @Required | 必要值校验(值不能为 null undefined NaN) | | @IsDefined | 值定义校验等同于@Required | | @IsNotEmpty | 非空校验 | | @ValidateBy | 自定义校验规则 | | @IsLatitude | 校验维度 | | @IsLongitude | 校验经度 | | @IsLatLong | 校验经纬度 |

type check

| 注解 | 描述 | | ---------- | ---------------------------- | | @IsArray | 是否为数组 | | @IsBoolean | 是否为布尔 | | @IsDate | 是否为日期对象 | | @IsInt | 是否为整数 | | @IsNumber | 是否为数值包括整数和小数 | | @IsObject | 是否为对象(plain object) | | @IsString | 是否为字符串 |

string

| 注解 | 描述 | | ---------------- | --------------------------------------------------- | | @Contains | 字符串包含某个子串 | | @NotContains | 字符串不能包含个子串 | | @IsAscii | 校验 ASCII 字符串 | | @IsBase64 | 校验 Base64 字符串 | | @IsDecimalString | 校验小数字符串 例如'0.1' | | @IsEmail | 校验邮箱格式 | | @IsFQDN | 校验合法域名 (e.g. domain.com). | | @IsURL | 校验 url | | @IsIp | 校验 IP 地址 | | @IsPort | 校验端口 | | @IsJSONString | 校验标准 JSON 字符串 | | @IsMobilePhone | 校验手机号 | | @IsNumberString | 校验由数字组成的字符串 | | @IsUUID | 校验 uuid | | @Matches | 校验字符串是否满足某正则如@Matches('foo', /foo/i) | | @MaxLength | 字符串长度不能超过给定值 | | @MinLength | 字符串长度不能小于给定值 |

number

| 注解 | 描述 | | ----------- | ---------------- | | @IsNegative | 负数校验 | | @Positive | 正数校验 | | @Max | 数值不能大于某值 | | @Min | 数值不能小于某值 |

Array

| 注解 | 描述 | | -------------- | -------------------------- | | @ArrayContain | 数组包含某个子数组 | | @ArrayMaxSize | 数组最大长度不能超过某个值 | | @ArrayMinSize | 数组最小长度不能低于某个值 | | @ArrayNotEmpty | 非空数组 |

Object

| 注解 | 描述 | | --------------- | -------- | | @ObjectNotEmpty | 非空对象 |

Date

| 注解 | 描述 | | -------- | ------------------ | | @MaxDate | 不允许超过某个日期 | | @MinDate | 不允许低于某个日期 |