Skip to content

AmauryD/fastest-validator-decorators

master
Switch branches/tags
Code

Latest commit

 

Git stats

Files

Permalink
Failed to load latest commit information.
Type
Name
Latest commit message
Commit time
 
 
src
 
 
 
 
 
 
 
 
 
 
 
 

npm npm GitHub issues GitHub license

Fastest Validator Decorators

Decorators for fastest-validator

Example usage

import {
  Schema,
  Array,
  Nested,
  UUID,
  Enum,
  Email,
  Number,
  getSchema,
  validate,
  validateOrReject
} from "fastest-validator-decorators";

@Schema(true)
class Entity1 {
  @Array({ items: "string"})
  prop1: string[];
}

@Schema()
class Entity2 {
  @UUID()
  prop1: string;

  @Enum({ values : ["one", "two"] })
  prop2: "one" | "two";

  @Email()
  prop3: string;

  @Number({ positive: true })
  prop4: number;

  @Nested()
  prop5: Entity1;
}

const schema = getSchema(Entity2); // get the fastest-validator schema
{
  $$strict: false,
  prop1: { type: "uuid" },
  prop2: { type: "enum", values: ["one", "two"] },
  prop3: { type: "email" },
  prop4: { type: "number", positive: true, convert: true },
  prop5: { type: "object", strict: true, props: {
    prop1: { type: "array", items: "string" }
  }}
}

const entity = new Entity2();
entity.prop1 = "thiswillfail";
entity.prop2 = "one";
entity.prop3 = "some@email.com";
entity.prop4 = -10;
entity.prop5 = new Entity1();

const result = validate(entity); // returns true or fastest-validator errors
const result = await validateOrReject(entity); // returns true or throws fastest-validator errors

The SchemaBase utility class reduces the verbosity of instantiating new objects by calling Object.assign in the constructor and provides a validate() method.

@Schema()
const Entity extends SchemaBase {
  @Email()
  email: string;
}

const entity = new Entity({ email: 'some@email.com' });
const result = entity.validate();

Setup

Install the package

npm install --save fastest-validator-decorators

Add the following to your tsconfig.json

"experimentalDecorators": true
"emitDecoratorMetadata": true

Available decorators

All decorators accept an object of options that apply to the type being used, for a full list of options please refer to the fastest-validator documentation.

@Schema(strict=false, messages={}) - Schema decorator. @Schema({ strict = false, async = false }, messages={}) - Schema decorator.

@Field({}) - Generic decorator, no default properties set. Will apply all options to the schema.

@String({}) - Applies { type: "string", empty: false }

@Boolean({}) - Applies { type: "boolean" }

@Number({}) - Applies { type: "number", convert: true }

@UUID({}) - Applies { type: "uuid" }

@ObjectId({}) - Applies { type: "objectid" }

@Email({}) - Applies { type: "email" }

@Date({}) - Applies { type: "date" }

@Enum({}) - Applies { type: "enum" }

@Array({}) - Applies { type: "array" }

@Equal({}) - Applies { type: "equal" }

@Instance({}) - Applies { type: "class" }

@Currency({}) - Applies { type: "currency" }

@Func({}) - Applies { type: "function" }

@Luhn({}) - Applies { type: "luhn" }

@Mac({}) - Applies { type: "mac" }

@Url({}) - Applies { type: "url" }

@Any({}) - Applies { type: "any" }

@Nested({}) - Applies { type: "object", props: {} } (The props are gathered from the nested schema)

@Custom({}) - Applies { type: "custom" }

@Custom({
  check (value: number, errors: {type: string, actual: number}[]){
    if (value % 2 !== 0) {
      errors.push({ type: "even", actual : value });
    }
    return value;
  }
})

Async support

In order to a schema to be async , you must add the async: true to SchemaOptions.

⚠️ Be carefull, when enabling async option, the return of the validate function becomes a Promise.

@Schema({
  async: true,
  strict: true
})
class User {
  @Custom({
    async check (value: string, errors: {type: string, actual: string}[]) {
      const isUserInDB = await db.checkUserName(value);
      if (isUserInDB) {
        errors.push({ type: "unique", actual : value });
      }
      return value;
    },
  })
  username!: string;
}

const user = new User();
user.username = "James Bond";
const result = await validate(user);

Available methods

getSchema() - Returns the fastest-validator schema for a given class

validate() - Returns true or fastest-validator errors for a given instance

validateOrReject() - Returns true or throws fastest-validator errors for a given instance

License

Licensed under the MIT license.