Skip to content

Commit

Permalink
Merge branch '2.x'
Browse files Browse the repository at this point in the history
  • Loading branch information
AmauryD committed Oct 22, 2022
2 parents 089f247 + 9013e87 commit 6b59341
Show file tree
Hide file tree
Showing 15 changed files with 1,156 additions and 987 deletions.
126 changes: 126 additions & 0 deletions MIGRATING.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
# Moving From 1.x to 2.x

## SchemaBase has been removed

The `SchemaBase` class has been removed. This class was overriding the constructor and may cause problems in the future.

The user is now responsible to handle property assignment to the class manually.

Here's a simple function replacing the SchemaBase's behavior.

```ts
function validateFromPayload(validationClass: any, payload: Record<string, any>) {
const validationClassInstance = new validationClass();
Object.assign(validationClassInstance,payload);
return validate(validationClassInstance);
}
```

### Before

```ts
@Schema(true)
export class User extends SchemaBase {
@String()
username: string;
}

const user = new User({
username: 'AmauryD'
});
const validated = user.validate();
```

### After

```ts
@Schema({
strict: true
})
export class User {
@String()
username: string;
}
const validated = validateFromPayload(User, {
username: 'AmauryD'
});
```


## Fastest-validator is now a peerDependency

`fastest-validator` has been moved to peerDependencies. So it needs to be installed in your project using your favorite package manager.

## Decorators are only applying "type" property as default.

The old decorators were applying some properties by default (like converting numbers). This behavior was confusing and was removed. User needs to explicitly tell fastest validator to apply a specific validation option.

### Before

`@Number()`

- applies `{ type: "number", convert: true }`

### After

`@Number()`

- applies `{ type: "number" }`


## Schema first option is now an object.

For better readability the first option to the @Schema decorator is an object.

### Before

```ts
// applies strict
@Schema(true)
class X {}
```

### After

```ts
// applies strict
@Schema({
strict: true
})
class X {}
```

## Schema second option has changed.

Before, second option was used to create only custom validation messages. It has been replaced by a more flexible option `ValidatorConstructorOptions`. You need to wrap your old message object in a message key in order to migrate.

### Before

```ts
// applies strict
@Schema(true, {
evenNumber: "The '{field}' field must be an even number! Actual: {actual}"
})
class X {}
```

### After

```ts
// applies strict
@Schema({
strict: true
}, {
messages: {
// Register our new error message text
evenNumber: "The '{field}' field must be an even number! Actual: {actual}"
},
// other fastest validator options ...
plugins: [],
})
class X {}
```

## Decorators are fully typed.

All decorators now provide typescript auto-completion. The types are directly from fastest-validator package.
38 changes: 16 additions & 22 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
# Fastest Validator Decorators
> Decorators for [fastest-validator](https://github.com/icebob/fastest-validator#readme)
:boom: Coming from 1.x ? See the [Migration Guide](MIGRATING.md).

## Example usage

```js
Expand All @@ -22,7 +24,9 @@ import {
validateOrReject
} from "fastest-validator-decorators";

@Schema(true)
@Schema({
strict: true
})
class Entity1 {
@Array({ items: "string"})
prop1: string[];
Expand Down Expand Up @@ -52,7 +56,7 @@ const schema = getSchema(Entity2); // get the fastest-validator schema
prop1: { type: "uuid" },
prop2: { type: "enum", values: ["one", "two"] },
prop3: { type: "email" },
prop4: { type: "number", positive: true, convert: true },
prop4: { type: "number", positive: true },
prop5: { type: "object", strict: true, props: {
prop1: { type: "array", items: "string" }
}}
Expand All @@ -69,28 +73,15 @@ 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.

:mega: This `SchemaBase` approach will probably be removed in 2.x release. See [#27](https://github.com/AmauryD/fastest-validator-decorators/issues/27).

```js
@Schema()
class Entity extends SchemaBase {
@Email()
email: string;
}

const entity = new Entity({ email: '[email protected]' });
const result = entity.validate();
```

## Setup

Install the package
```
npm install --save fastest-validator-decorators
npm install --save fastest-validator-decorators fastest-validator
```

:sparkles: fastest-validator is a peerDependency.

Add the following to your tsconfig.json
```
"experimentalDecorators": true
Expand All @@ -101,16 +92,15 @@ Add the following to your tsconfig.json

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](https://www.npmjs.com/package/fastest-validator).

**@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({})**](https://github.com/icebob/fastest-validator#string) - Applies { type: "string", empty: false }
[**@String({})**](https://github.com/icebob/fastest-validator#string) - Applies { type: "string" }

[**@Boolean({})**](https://github.com/icebob/fastest-validator#boolean) - Applies { type: "boolean" }

[**@Number({})**](https://github.com/icebob/fastest-validator#number) - Applies { type: "number", convert: true }
[**@Number({})**](https://github.com/icebob/fastest-validator#number) - Applies { type: "number" }

[**@UUID({})**](https://github.com/icebob/fastest-validator#uuid) - Applies { type: "uuid" }

Expand Down Expand Up @@ -142,6 +132,8 @@ All decorators accept an object of options that apply to the type being used, fo

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

**@NestedArray({ validator: `<ValidatorSchema>` })** - Applies { type: "array", "items": { type :"object", props: { ... } }} (The props are gathered from the nested schema)

[**@Custom({})**](https://github.com/icebob/fastest-validator#custom-validator) - Applies { type: "custom" }

```ts
Expand All @@ -157,7 +149,7 @@ All decorators accept an object of options that apply to the type being used, fo

## Async support

In order to a schema to be async , you must add the `async: true` to `SchemaOptions`.
In order to a schema to be async , you must add the `async: true` to [SchemaOptions](https://github.com/AmauryD/fastest-validator-decorators/blob/6e34ebf41eae5ed60bb1f8bf0dc4379e72136f4e/src/schema.ts#L7).

:warning: Be carefull, when enabling async option, the return of the validate function becomes a [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).

Expand Down Expand Up @@ -192,5 +184,7 @@ const result = await validate(user);

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


## License
Licensed under the MIT license.

35 changes: 19 additions & 16 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "fastest-validator-decorators",
"author": "Toby de Havilland",
"version": "1.3.1",
"version": "2.0.0-alpha.2",
"description": "Fastest validator decorators",
"license": "MIT",
"repository": {
Expand All @@ -21,8 +21,7 @@
"prepublish": "pnpm run test && pnpm run build"
},
"files": [
"dist/index.d.ts",
"dist/index.js"
"dist/src"
],
"keywords": [
"validation",
Expand All @@ -33,22 +32,26 @@
"typescript",
"decorators"
],
"main": "dist/index.js",
"types": "dist/index.d.ts",
"main": "dist/src/index.js",
"types": "dist/src/index.d.ts",
"devDependencies": {
"@types/jest": "^29.0.0",
"@types/node": "^18.7.14",
"@typescript-eslint/eslint-plugin": "^5.36.1",
"@typescript-eslint/parser": "^5.36.1",
"eslint": "^8.23.0",
"jest": "^29.0.2",
"ts-jest": "^28.0.8",
"@types/jest": "^29.2.0",
"@types/node": "^18.11.3",
"@typescript-eslint/eslint-plugin": "^5.40.1",
"@typescript-eslint/parser": "^5.40.1",
"eslint": "^8.26.0",
"fastest-validator": "~1.15.0",
"jest": "^29.2.1",
"ts-jest": "^29.0.3",
"ts-node": "^10.9.1",
"typescript": "^4.8.2"
"typescript": "^4.8.4"
},
"peerDependencies": {
"fastest-validator": "~1.15.0"
},
"dependencies": {
"fastest-validator": "^1.15.0",
"reflect-metadata": "^0.1.13"
"reflect-metadata": "~0.1.13",
"type-fest": "~3.1.0"
},
"jest": {
"coverageDirectory": "<rootDir>/coverage",
Expand All @@ -62,7 +65,7 @@
"^.+\\.(ts|tsx)$": "ts-jest"
},
"testMatch": [
"**/*.spec.(ts|js)"
"**/*.test.(ts|js)"
],
"testPathIgnorePatterns": [
"<rootDir>/dist/"
Expand Down
Loading

0 comments on commit 6b59341

Please sign in to comment.