@celljs/validation 0.0.0-stage → 4.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +33 -2
- package/cell.yml +4 -0
- package/esm/node/index.d.ts +1 -0
- package/esm/node/index.js +2 -0
- package/esm/node/index.js.map +1 -0
- package/esm/node/module.d.ts +3 -0
- package/esm/node/module.js +4 -0
- package/esm/node/module.js.map +1 -0
- package/esm/node/validation-pipe.d.ts +31 -0
- package/esm/node/validation-pipe.js +102 -0
- package/esm/node/validation-pipe.js.map +1 -0
- package/esm/package.json +3 -0
- package/lib/node/index.d.ts +2 -0
- package/lib/node/index.d.ts.map +1 -0
- package/lib/node/index.js +18 -0
- package/lib/node/index.js.map +1 -0
- package/lib/node/module.d.ts +4 -0
- package/lib/node/module.d.ts.map +1 -0
- package/lib/node/module.js +6 -0
- package/lib/node/module.js.map +1 -0
- package/lib/node/validation-pipe.d.ts +32 -0
- package/lib/node/validation-pipe.d.ts.map +1 -0
- package/lib/node/validation-pipe.js +105 -0
- package/lib/node/validation-pipe.js.map +1 -0
- package/lib/node/validation-pipe.spec.d.ts +2 -0
- package/lib/node/validation-pipe.spec.d.ts.map +1 -0
- package/lib/node/validation-pipe.spec.js +90 -0
- package/lib/node/validation-pipe.spec.js.map +1 -0
- package/lib/package.spec.d.ts +2 -0
- package/lib/package.spec.d.ts.map +1 -0
- package/lib/package.spec.js +7 -0
- package/lib/package.spec.js.map +1 -0
- package/package.json +68 -4
- package/src/node/index.ts +1 -0
- package/src/node/module.ts +4 -0
- package/src/node/validation-pipe.spec.ts +83 -0
- package/src/node/validation-pipe.ts +104 -0
- package/src/package.spec.ts +5 -0
package/README.md
CHANGED
|
@@ -1,3 +1,34 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Cell - Validation Component
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Add `@celljs/validation` to the dependencies to check request data: a controller or RPC parameter whose type is a class becomes an instance of it ([class-transformer](https://github.com/typestack/class-transformer)) and is validated with its [class-validator](https://github.com/typestack/class-validator) decorators. Failures answer `400` with the errors as JSON.
|
|
4
|
+
|
|
5
|
+
```ts
|
|
6
|
+
import { IsInt, IsString, Min } from 'class-validator';
|
|
7
|
+
|
|
8
|
+
export class CreateUser {
|
|
9
|
+
@IsString()
|
|
10
|
+
name: string;
|
|
11
|
+
|
|
12
|
+
@IsInt()
|
|
13
|
+
@Min(0)
|
|
14
|
+
age: number;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
@Controller('users')
|
|
18
|
+
export class UserController {
|
|
19
|
+
@Post()
|
|
20
|
+
create(@Body() user: CreateUser) { ... }
|
|
21
|
+
}
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
Without this package `@celljs/web` passes such parameters the plain request data, and still converts `String`, `Number`, `Boolean` and `Date` parameters (`TypeConversionPipe`).
|
|
25
|
+
|
|
26
|
+
```yaml
|
|
27
|
+
backend:
|
|
28
|
+
cell:
|
|
29
|
+
validation:
|
|
30
|
+
detailedOutputDisabled: false # true: answer 400 without the errors
|
|
31
|
+
transformEnabled: true # false: hand the method the request data, not the instance
|
|
32
|
+
transformOptions: {} # options of plainToInstance
|
|
33
|
+
validatorOptions: {} # options of validate, e.g. whitelist: true
|
|
34
|
+
```
|
package/cell.yml
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from './validation-pipe.js';
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/node/index.ts"],"names":[],"mappings":"AAAA,cAAc,mBAAmB,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"module.js","sourceRoot":"","sources":["../../src/node/module.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AACxC,OAAO,SAAS,CAAC;AAEjB,eAAe,QAAQ,EAAE,CAAC"}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { ArgumentMetadata, PipeTransform } from '@celljs/web';
|
|
2
|
+
/** `cell.validation`. */
|
|
3
|
+
export interface ValidationOptions {
|
|
4
|
+
/** Answer 400 without the errors. Default false. */
|
|
5
|
+
detailedOutputDisabled?: boolean;
|
|
6
|
+
/** Hand the method the instance of the parameter class; otherwise the request data it was made from. Default true. */
|
|
7
|
+
transformEnabled?: boolean;
|
|
8
|
+
/** Options of class-transformer's `plainToInstance` / `instanceToPlain`. */
|
|
9
|
+
transformOptions?: Record<string, unknown>;
|
|
10
|
+
/** Options of class-validator's `validate`. */
|
|
11
|
+
validatorOptions?: Record<string, unknown>;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Turns request data into an instance of the parameter class with class-transformer and checks it with
|
|
15
|
+
* class-validator: `@Body() user: CreateUser` gets a `CreateUser` whose decorators (`@IsString()`...) hold,
|
|
16
|
+
* or the request answers 400 with the errors ({@link ValidationErrors}).
|
|
17
|
+
*/
|
|
18
|
+
export declare class ValidationPipe implements PipeTransform<any> {
|
|
19
|
+
protected options?: ValidationOptions;
|
|
20
|
+
readonly priority = 900;
|
|
21
|
+
transform(value: any, { argType }: ArgumentMetadata): Promise<any>;
|
|
22
|
+
private stripProtoKeys;
|
|
23
|
+
/**
|
|
24
|
+
* Request data: primitives, arrays and plain objects, as parsed from JSON, query strings or RPC
|
|
25
|
+
* messages. Objects the framework passes in (request, response, session, cookies, errors) are
|
|
26
|
+
* class instances and pass through: converting them would copy them property by property, which
|
|
27
|
+
* never ends for the circular request and response.
|
|
28
|
+
*/
|
|
29
|
+
private isData;
|
|
30
|
+
private isPrimitive;
|
|
31
|
+
}
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
2
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
3
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
4
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
5
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
6
|
+
};
|
|
7
|
+
var __metadata = (this && this.__metadata) || function (k, v) {
|
|
8
|
+
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
9
|
+
};
|
|
10
|
+
import { Component, Value } from '@celljs/core';
|
|
11
|
+
import { PipeTransform, ValidationErrors } from '@celljs/web';
|
|
12
|
+
import { instanceToPlain, plainToInstance } from 'class-transformer';
|
|
13
|
+
import { validate } from 'class-validator';
|
|
14
|
+
/** Types the pipe leaves to `TypeConversionPipe` of `@celljs/web` or passes as they are. */
|
|
15
|
+
const PLAIN_TYPES = [String, Number, Boolean, Date, Object, Array];
|
|
16
|
+
/**
|
|
17
|
+
* Turns request data into an instance of the parameter class with class-transformer and checks it with
|
|
18
|
+
* class-validator: `@Body() user: CreateUser` gets a `CreateUser` whose decorators (`@IsString()`...) hold,
|
|
19
|
+
* or the request answers 400 with the errors ({@link ValidationErrors}).
|
|
20
|
+
*/
|
|
21
|
+
let ValidationPipe = class ValidationPipe {
|
|
22
|
+
constructor() {
|
|
23
|
+
this.priority = 900;
|
|
24
|
+
}
|
|
25
|
+
async transform(value, { argType }) {
|
|
26
|
+
if (!argType || PLAIN_TYPES.includes(argType) || !this.isData(value)) {
|
|
27
|
+
return value;
|
|
28
|
+
}
|
|
29
|
+
const opts = this.options || {};
|
|
30
|
+
const originalValue = value;
|
|
31
|
+
value = value === null ? {} : value;
|
|
32
|
+
const isNil = value !== originalValue;
|
|
33
|
+
const isPrimitive = this.isPrimitive(value);
|
|
34
|
+
this.stripProtoKeys(value);
|
|
35
|
+
let entity = plainToInstance(argType, value, opts.transformOptions);
|
|
36
|
+
const originalEntity = entity;
|
|
37
|
+
if (entity.constructor !== argType) {
|
|
38
|
+
if (isPrimitive) {
|
|
39
|
+
// Validate a primitive against the declared class, then hand back the primitive.
|
|
40
|
+
entity = { constructor: argType };
|
|
41
|
+
}
|
|
42
|
+
else {
|
|
43
|
+
entity.constructor = argType;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
const errors = await validate(entity, opts.validatorOptions);
|
|
47
|
+
if (errors.length > 0) {
|
|
48
|
+
throw new ValidationErrors(opts.detailedOutputDisabled ? undefined : errors);
|
|
49
|
+
}
|
|
50
|
+
if (isPrimitive) {
|
|
51
|
+
entity = originalEntity;
|
|
52
|
+
}
|
|
53
|
+
if (opts.transformEnabled !== false) {
|
|
54
|
+
return entity;
|
|
55
|
+
}
|
|
56
|
+
if (isNil) {
|
|
57
|
+
return originalValue;
|
|
58
|
+
}
|
|
59
|
+
return opts.validatorOptions && Object.keys(opts.validatorOptions).length > 0
|
|
60
|
+
? instanceToPlain(entity, opts.transformOptions)
|
|
61
|
+
: value;
|
|
62
|
+
}
|
|
63
|
+
stripProtoKeys(value) {
|
|
64
|
+
if (typeof value !== 'object') {
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
delete value.__proto__;
|
|
68
|
+
for (const key of Object.keys(value)) {
|
|
69
|
+
if (typeof value[key] === 'object' && value[key]) {
|
|
70
|
+
this.stripProtoKeys(value[key]);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Request data: primitives, arrays and plain objects, as parsed from JSON, query strings or RPC
|
|
76
|
+
* messages. Objects the framework passes in (request, response, session, cookies, errors) are
|
|
77
|
+
* class instances and pass through: converting them would copy them property by property, which
|
|
78
|
+
* never ends for the circular request and response.
|
|
79
|
+
*/
|
|
80
|
+
isData(value) {
|
|
81
|
+
if (typeof value === 'function') {
|
|
82
|
+
return false;
|
|
83
|
+
}
|
|
84
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value)) {
|
|
85
|
+
return true;
|
|
86
|
+
}
|
|
87
|
+
const proto = Object.getPrototypeOf(value);
|
|
88
|
+
return proto === Object.prototype || proto === null;
|
|
89
|
+
}
|
|
90
|
+
isPrimitive(value) {
|
|
91
|
+
return ['number', 'boolean', 'string'].indexOf(typeof value) !== -1;
|
|
92
|
+
}
|
|
93
|
+
};
|
|
94
|
+
__decorate([
|
|
95
|
+
Value('cell.validation'),
|
|
96
|
+
__metadata("design:type", Object)
|
|
97
|
+
], ValidationPipe.prototype, "options", void 0);
|
|
98
|
+
ValidationPipe = __decorate([
|
|
99
|
+
Component(PipeTransform)
|
|
100
|
+
], ValidationPipe);
|
|
101
|
+
export { ValidationPipe };
|
|
102
|
+
//# sourceMappingURL=validation-pipe.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"validation-pipe.js","sourceRoot":"","sources":["../../src/node/validation-pipe.ts"],"names":[],"mappings":";;;;;;;;;AAAA,OAAO,EAAE,SAAS,EAAE,KAAK,EAAE,MAAM,cAAc,CAAC;AAChD,OAAO,EAAoB,aAAa,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAChF,OAAO,EAAE,eAAe,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AACrE,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAc3C,4FAA4F;AAC5F,MAAM,WAAW,GAAe,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,KAAK,CAAC,CAAC;AAE/E;;;;GAIG;AAEI,IAAM,cAAc,GAApB,MAAM,cAAc;IAApB;QAKM,aAAQ,GAAG,GAAG,CAAC;IAwE5B,CAAC;IAtEG,KAAK,CAAC,SAAS,CAAC,KAAU,EAAE,EAAE,OAAO,EAAoB;QACrD,IAAI,CAAC,OAAO,IAAI,WAAW,CAAC,QAAQ,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC;YACnE,OAAO,KAAK,CAAC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Ea;IADT,KAAK,CAAC,iBAAiB,CAAC;;+CACa;AAH7B,cAAc;IAD1B,SAAS,CAAC,aAAa,CAAC;GACZ,cAAc,CA6E1B"}
|
package/esm/package.json
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/node/index.ts"],"names":[],"mappings":"AAAA,cAAc,mBAAmB,CAAC"}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
14
|
+
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
|
+
};
|
|
16
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
+
__exportStar(require("./validation-pipe"), exports);
|
|
18
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/node/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,oDAAkC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"module.d.ts","sourceRoot":"","sources":["../../src/node/module.ts"],"names":[],"mappings":"AACA,OAAO,SAAS,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"module.js","sourceRoot":"","sources":["../../src/node/module.ts"],"names":[],"mappings":";;AAAA,uCAAwC;AACxC,mBAAiB;kBAEF,IAAA,eAAQ,GAAE"}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { ArgumentMetadata, PipeTransform } from '@celljs/web';
|
|
2
|
+
/** `cell.validation`. */
|
|
3
|
+
export interface ValidationOptions {
|
|
4
|
+
/** Answer 400 without the errors. Default false. */
|
|
5
|
+
detailedOutputDisabled?: boolean;
|
|
6
|
+
/** Hand the method the instance of the parameter class; otherwise the request data it was made from. Default true. */
|
|
7
|
+
transformEnabled?: boolean;
|
|
8
|
+
/** Options of class-transformer's `plainToInstance` / `instanceToPlain`. */
|
|
9
|
+
transformOptions?: Record<string, unknown>;
|
|
10
|
+
/** Options of class-validator's `validate`. */
|
|
11
|
+
validatorOptions?: Record<string, unknown>;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Turns request data into an instance of the parameter class with class-transformer and checks it with
|
|
15
|
+
* class-validator: `@Body() user: CreateUser` gets a `CreateUser` whose decorators (`@IsString()`...) hold,
|
|
16
|
+
* or the request answers 400 with the errors ({@link ValidationErrors}).
|
|
17
|
+
*/
|
|
18
|
+
export declare class ValidationPipe implements PipeTransform<any> {
|
|
19
|
+
protected options?: ValidationOptions;
|
|
20
|
+
readonly priority = 900;
|
|
21
|
+
transform(value: any, { argType }: ArgumentMetadata): Promise<any>;
|
|
22
|
+
private stripProtoKeys;
|
|
23
|
+
/**
|
|
24
|
+
* Request data: primitives, arrays and plain objects, as parsed from JSON, query strings or RPC
|
|
25
|
+
* messages. Objects the framework passes in (request, response, session, cookies, errors) are
|
|
26
|
+
* class instances and pass through: converting them would copy them property by property, which
|
|
27
|
+
* never ends for the circular request and response.
|
|
28
|
+
*/
|
|
29
|
+
private isData;
|
|
30
|
+
private isPrimitive;
|
|
31
|
+
}
|
|
32
|
+
//# sourceMappingURL=validation-pipe.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"validation-pipe.d.ts","sourceRoot":"","sources":["../../src/node/validation-pipe.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,gBAAgB,EAAE,aAAa,EAAoB,MAAM,aAAa,CAAC;AAIhF,yBAAyB;AACzB,MAAM,WAAW,iBAAiB;IAC9B,oDAAoD;IACpD,sBAAsB,CAAC,EAAE,OAAO,CAAC;IACjC,sHAAsH;IACtH,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAC3B,4EAA4E;IAC5E,gBAAgB,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAC3C,+CAA+C;IAC/C,gBAAgB,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CAC9C;AAKD;;;;GAIG;AACH,qBACa,cAAe,YAAW,aAAa,CAAC,GAAG,CAAC;IAGrD,SAAS,CAAC,OAAO,CAAC,EAAE,iBAAiB,CAAC;IAEtC,QAAQ,CAAC,QAAQ,OAAO;IAElB,SAAS,CAAC,KAAK,EAAE,GAAG,EAAE,EAAE,OAAO,EAAE,EAAE,gBAAgB,GAAG,OAAO,CAAC,GAAG,CAAC,CAoCvE;IAED,OAAO,CAAC,cAAc;IAYtB;;;;;OAKG;IACH,OAAO,CAAC,MAAM;IAWd,OAAO,CAAC,WAAW;CAGtB"}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
3
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
4
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
5
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
6
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
7
|
+
};
|
|
8
|
+
var __metadata = (this && this.__metadata) || function (k, v) {
|
|
9
|
+
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
10
|
+
};
|
|
11
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
|
+
exports.ValidationPipe = void 0;
|
|
13
|
+
const core_1 = require("@celljs/core");
|
|
14
|
+
const web_1 = require("@celljs/web");
|
|
15
|
+
const class_transformer_1 = require("class-transformer");
|
|
16
|
+
const class_validator_1 = require("class-validator");
|
|
17
|
+
/** Types the pipe leaves to `TypeConversionPipe` of `@celljs/web` or passes as they are. */
|
|
18
|
+
const PLAIN_TYPES = [String, Number, Boolean, Date, Object, Array];
|
|
19
|
+
/**
|
|
20
|
+
* Turns request data into an instance of the parameter class with class-transformer and checks it with
|
|
21
|
+
* class-validator: `@Body() user: CreateUser` gets a `CreateUser` whose decorators (`@IsString()`...) hold,
|
|
22
|
+
* or the request answers 400 with the errors ({@link ValidationErrors}).
|
|
23
|
+
*/
|
|
24
|
+
let ValidationPipe = class ValidationPipe {
|
|
25
|
+
constructor() {
|
|
26
|
+
this.priority = 900;
|
|
27
|
+
}
|
|
28
|
+
async transform(value, { argType }) {
|
|
29
|
+
if (!argType || PLAIN_TYPES.includes(argType) || !this.isData(value)) {
|
|
30
|
+
return value;
|
|
31
|
+
}
|
|
32
|
+
const opts = this.options || {};
|
|
33
|
+
const originalValue = value;
|
|
34
|
+
value = value === null ? {} : value;
|
|
35
|
+
const isNil = value !== originalValue;
|
|
36
|
+
const isPrimitive = this.isPrimitive(value);
|
|
37
|
+
this.stripProtoKeys(value);
|
|
38
|
+
let entity = (0, class_transformer_1.plainToInstance)(argType, value, opts.transformOptions);
|
|
39
|
+
const originalEntity = entity;
|
|
40
|
+
if (entity.constructor !== argType) {
|
|
41
|
+
if (isPrimitive) {
|
|
42
|
+
// Validate a primitive against the declared class, then hand back the primitive.
|
|
43
|
+
entity = { constructor: argType };
|
|
44
|
+
}
|
|
45
|
+
else {
|
|
46
|
+
entity.constructor = argType;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
const errors = await (0, class_validator_1.validate)(entity, opts.validatorOptions);
|
|
50
|
+
if (errors.length > 0) {
|
|
51
|
+
throw new web_1.ValidationErrors(opts.detailedOutputDisabled ? undefined : errors);
|
|
52
|
+
}
|
|
53
|
+
if (isPrimitive) {
|
|
54
|
+
entity = originalEntity;
|
|
55
|
+
}
|
|
56
|
+
if (opts.transformEnabled !== false) {
|
|
57
|
+
return entity;
|
|
58
|
+
}
|
|
59
|
+
if (isNil) {
|
|
60
|
+
return originalValue;
|
|
61
|
+
}
|
|
62
|
+
return opts.validatorOptions && Object.keys(opts.validatorOptions).length > 0
|
|
63
|
+
? (0, class_transformer_1.instanceToPlain)(entity, opts.transformOptions)
|
|
64
|
+
: value;
|
|
65
|
+
}
|
|
66
|
+
stripProtoKeys(value) {
|
|
67
|
+
if (typeof value !== 'object') {
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
delete value.__proto__;
|
|
71
|
+
for (const key of Object.keys(value)) {
|
|
72
|
+
if (typeof value[key] === 'object' && value[key]) {
|
|
73
|
+
this.stripProtoKeys(value[key]);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Request data: primitives, arrays and plain objects, as parsed from JSON, query strings or RPC
|
|
79
|
+
* messages. Objects the framework passes in (request, response, session, cookies, errors) are
|
|
80
|
+
* class instances and pass through: converting them would copy them property by property, which
|
|
81
|
+
* never ends for the circular request and response.
|
|
82
|
+
*/
|
|
83
|
+
isData(value) {
|
|
84
|
+
if (typeof value === 'function') {
|
|
85
|
+
return false;
|
|
86
|
+
}
|
|
87
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value)) {
|
|
88
|
+
return true;
|
|
89
|
+
}
|
|
90
|
+
const proto = Object.getPrototypeOf(value);
|
|
91
|
+
return proto === Object.prototype || proto === null;
|
|
92
|
+
}
|
|
93
|
+
isPrimitive(value) {
|
|
94
|
+
return ['number', 'boolean', 'string'].indexOf(typeof value) !== -1;
|
|
95
|
+
}
|
|
96
|
+
};
|
|
97
|
+
exports.ValidationPipe = ValidationPipe;
|
|
98
|
+
__decorate([
|
|
99
|
+
(0, core_1.Value)('cell.validation'),
|
|
100
|
+
__metadata("design:type", Object)
|
|
101
|
+
], ValidationPipe.prototype, "options", void 0);
|
|
102
|
+
exports.ValidationPipe = ValidationPipe = __decorate([
|
|
103
|
+
(0, core_1.Component)(web_1.PipeTransform)
|
|
104
|
+
], ValidationPipe);
|
|
105
|
+
//# sourceMappingURL=validation-pipe.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"validation-pipe.js","sourceRoot":"","sources":["../../src/node/validation-pipe.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,uCAAgD;AAChD,qCAAgF;AAChF,yDAAqE;AACrE,qDAA2C;AAc3C,4FAA4F;AAC5F,MAAM,WAAW,GAAe,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,KAAK,CAAC,CAAC;AAE/E;;;;GAIG;AAEI,IAAM,cAAc,GAApB,MAAM,cAAc;IAApB;QAKM,aAAQ,GAAG,GAAG,CAAC;IAwE5B,CAAC;IAtEG,KAAK,CAAC,SAAS,CAAC,KAAU,EAAE,EAAE,OAAO,EAAoB;QACrD,IAAI,CAAC,OAAO,IAAI,WAAW,CAAC,QAAQ,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC;YACnE,OAAO,KAAK,CAAC;QACjB,CAAC;QACD,MAAM,IAAI,GAAG,IAAI,CAAC,OAAO,IAAI,EAAE,CAAC;QAChC,MAAM,aAAa,GAAG,KAAK,CAAC;QAC5B,KAAK,GAAG,KAAK,KAAK,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CA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
{"version":3,"file":"validation-pipe.spec.d.ts","sourceRoot":"","sources":["../../src/node/validation-pipe.spec.ts"],"names":[],"mappings":""}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
3
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
4
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
5
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
6
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
7
|
+
};
|
|
8
|
+
var __metadata = (this && this.__metadata) || function (k, v) {
|
|
9
|
+
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
10
|
+
};
|
|
11
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
|
+
const bun_test_1 = require("bun:test");
|
|
13
|
+
const chai_1 = require("chai");
|
|
14
|
+
const class_validator_1 = require("class-validator");
|
|
15
|
+
const node_http_1 = require("node:http");
|
|
16
|
+
const node_net_1 = require("node:net");
|
|
17
|
+
const web_1 = require("@celljs/web");
|
|
18
|
+
const validation_pipe_1 = require("./validation-pipe");
|
|
19
|
+
class CreateUser {
|
|
20
|
+
}
|
|
21
|
+
__decorate([
|
|
22
|
+
(0, class_validator_1.IsString)(),
|
|
23
|
+
__metadata("design:type", String)
|
|
24
|
+
], CreateUser.prototype, "name", void 0);
|
|
25
|
+
__decorate([
|
|
26
|
+
(0, class_validator_1.IsOptional)(),
|
|
27
|
+
(0, class_validator_1.IsInt)(),
|
|
28
|
+
(0, class_validator_1.Min)(0),
|
|
29
|
+
__metadata("design:type", Number)
|
|
30
|
+
], CreateUser.prototype, "age", void 0);
|
|
31
|
+
class Cookies {
|
|
32
|
+
constructor(values) {
|
|
33
|
+
this.values = values;
|
|
34
|
+
}
|
|
35
|
+
get(name) {
|
|
36
|
+
return this.values[name];
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
function createPipe(options = { detailedOutputDisabled: false, transformEnabled: true }) {
|
|
40
|
+
const pipe = new validation_pipe_1.ValidationPipe();
|
|
41
|
+
pipe.options = options;
|
|
42
|
+
return pipe;
|
|
43
|
+
}
|
|
44
|
+
(0, bun_test_1.describe)('ValidationPipe', () => {
|
|
45
|
+
(0, bun_test_1.it)('passes the request and response through, whatever the parameter type', async () => {
|
|
46
|
+
const pipe = createPipe();
|
|
47
|
+
const request = new node_http_1.IncomingMessage(new node_net_1.Socket());
|
|
48
|
+
const response = new node_http_1.ServerResponse(request);
|
|
49
|
+
(0, chai_1.expect)(await pipe.transform(response, { argType: Object })).to.equal(response);
|
|
50
|
+
(0, chai_1.expect)(await pipe.transform(response, { argType: node_http_1.ServerResponse })).to.equal(response);
|
|
51
|
+
(0, chai_1.expect)(await pipe.transform(request, { argType: CreateUser })).to.equal(request);
|
|
52
|
+
});
|
|
53
|
+
(0, bun_test_1.it)('keeps other framework objects with their methods', async () => {
|
|
54
|
+
const cookies = new Cookies({ token: 'abc' });
|
|
55
|
+
const result = await createPipe().transform(cookies, { argType: CreateUser });
|
|
56
|
+
(0, chai_1.expect)(result).to.equal(cookies);
|
|
57
|
+
(0, chai_1.expect)(result.get('token')).to.equal('abc');
|
|
58
|
+
});
|
|
59
|
+
(0, bun_test_1.it)('turns request data into the parameter class and validates it', async () => {
|
|
60
|
+
var _a, _b;
|
|
61
|
+
const pipe = createPipe();
|
|
62
|
+
const user = await pipe.transform({ name: 'Tom', age: 3 }, { argType: CreateUser });
|
|
63
|
+
(0, chai_1.expect)(user).to.be.instanceOf(CreateUser);
|
|
64
|
+
(0, chai_1.expect)(user.name).to.equal('Tom');
|
|
65
|
+
const error = await pipe.transform({ name: 1, age: -1 }, { argType: CreateUser }).catch(e => e);
|
|
66
|
+
(0, chai_1.expect)(error).to.be.instanceOf(web_1.ValidationErrors);
|
|
67
|
+
(0, chai_1.expect)((_a = error.errors) === null || _a === void 0 ? void 0 : _a.map(e => e.property)).to.deep.equal(['name', 'age']);
|
|
68
|
+
(0, chai_1.expect)((_b = error.errors) === null || _b === void 0 ? void 0 : _b[0].constraints).to.have.property('isString');
|
|
69
|
+
});
|
|
70
|
+
(0, bun_test_1.it)('answers without the errors when detailedOutputDisabled is set', async () => {
|
|
71
|
+
const error = await createPipe({ detailedOutputDisabled: true }).transform({ name: 1 }, { argType: CreateUser }).catch(e => e);
|
|
72
|
+
(0, chai_1.expect)(error).to.be.instanceOf(web_1.ValidationErrors);
|
|
73
|
+
(0, chai_1.expect)(error.errors).to.equal(undefined);
|
|
74
|
+
});
|
|
75
|
+
(0, bun_test_1.it)('hands back the request data when transformEnabled is false', async () => {
|
|
76
|
+
const data = { name: 'Tom' };
|
|
77
|
+
(0, chai_1.expect)(await createPipe({ transformEnabled: false }).transform(data, { argType: CreateUser })).to.equal(data);
|
|
78
|
+
// null is validated as {}: a required property fails.
|
|
79
|
+
(0, chai_1.expect)(await createPipe({ transformEnabled: false }).transform(null, { argType: CreateUser }).catch(e => e)).to.be.instanceOf(web_1.ValidationErrors);
|
|
80
|
+
});
|
|
81
|
+
(0, bun_test_1.it)('leaves primitive, Date, Object and Array parameters to the other pipes', async () => {
|
|
82
|
+
const pipe = createPipe();
|
|
83
|
+
const data = { a: { b: 1 } };
|
|
84
|
+
(0, chai_1.expect)(await pipe.transform(data, { argType: Object })).to.equal(data);
|
|
85
|
+
(0, chai_1.expect)(await pipe.transform([1, 2], { argType: Array })).to.deep.equal([1, 2]);
|
|
86
|
+
(0, chai_1.expect)(await pipe.transform('5', { argType: Number })).to.equal('5');
|
|
87
|
+
(0, chai_1.expect)(await pipe.transform('5', {})).to.equal('5');
|
|
88
|
+
});
|
|
89
|
+
});
|
|
90
|
+
//# sourceMappingURL=validation-pipe.spec.js.map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AAI,CAAC,SAAS,CAAC,GAAG,EAAE,EAAE,OAAO,EAAE,MAAM,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;QACrE,IAAA,aAAM,EAAC,MAAM,IAAI,CAAC,SAAS,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IACxD,CAAC,CAAC,CAAC;AACP,CAAC,CAAC,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"package.spec.d.ts","sourceRoot":"","sources":["../src/package.spec.ts"],"names":[],"mappings":""}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
const bun_test_1 = require("bun:test");
|
|
4
|
+
(0, bun_test_1.describe)('validation package', () => {
|
|
5
|
+
(0, bun_test_1.it)('support code coverage statistics', () => { });
|
|
6
|
+
});
|
|
7
|
+
//# sourceMappingURL=package.spec.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"package.spec.js","sourceRoot":"","sources":["../src/package.spec.ts"],"names":[],"mappings":";;AAAA,uCAAwC;AACxC,IAAA,mBAAQ,EAAC,oBAAoB,EAAE,GAAG,EAAE;IAEhC,IAAA,aAAE,EAAC,kCAAkC,EAAE,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC;AACrD,CAAC,CAAC,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,70 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@celljs/validation",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "4.3.0",
|
|
4
|
+
"description": "Validates request data of Cell controllers and RPC services with class-validator",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"cell-component"
|
|
7
|
+
],
|
|
8
|
+
"homepage": "https://github.com/cellbang/cell",
|
|
9
|
+
"bugs": {
|
|
10
|
+
"url": "https://github.com/cellbang/cell/issues"
|
|
11
|
+
},
|
|
12
|
+
"repository": {
|
|
13
|
+
"type": "git",
|
|
14
|
+
"url": "https://github.com/cellbang/cell.git"
|
|
15
|
+
},
|
|
16
|
+
"license": "MIT",
|
|
17
|
+
"engines": {
|
|
18
|
+
"node": ">=18.0.0"
|
|
19
|
+
},
|
|
20
|
+
"main": "lib/node/index.js",
|
|
21
|
+
"typings": "lib/node/index.d.ts",
|
|
22
|
+
"files": [
|
|
23
|
+
"lib",
|
|
24
|
+
"esm",
|
|
25
|
+
"src",
|
|
26
|
+
"cell.yml"
|
|
27
|
+
],
|
|
28
|
+
"scripts": {
|
|
29
|
+
"build": "tsc -b && bun ../../scripts/build-esm.ts",
|
|
30
|
+
"clean": "rm -rf lib esm *.tsbuildinfo",
|
|
31
|
+
"test": "bun test --preload reflect-metadata ./lib",
|
|
32
|
+
"watch": "tsc -b -w --preserveWatchOutput"
|
|
33
|
+
},
|
|
34
|
+
"dependencies": {
|
|
35
|
+
"@celljs/core": "4.3.0",
|
|
36
|
+
"@celljs/web": "4.3.0",
|
|
37
|
+
"class-transformer": "^0.5.1",
|
|
38
|
+
"class-validator": "^0.14.4"
|
|
39
|
+
},
|
|
40
|
+
"publishConfig": {
|
|
41
|
+
"access": "public"
|
|
42
|
+
},
|
|
43
|
+
"exports": {
|
|
44
|
+
".": {
|
|
45
|
+
"import": "./esm/node/index.js",
|
|
46
|
+
"default": "./lib/node/index.js"
|
|
47
|
+
},
|
|
48
|
+
"./package.json": "./package.json",
|
|
49
|
+
"./lib/node": {
|
|
50
|
+
"import": "./esm/node/index.js",
|
|
51
|
+
"default": "./lib/node/index.js"
|
|
52
|
+
},
|
|
53
|
+
"./lib/*.js": {
|
|
54
|
+
"import": "./esm/*.js",
|
|
55
|
+
"default": "./lib/*.js"
|
|
56
|
+
},
|
|
57
|
+
"./lib/*": {
|
|
58
|
+
"import": "./esm/*.js",
|
|
59
|
+
"default": "./lib/*.js"
|
|
60
|
+
},
|
|
61
|
+
"./*": "./*"
|
|
62
|
+
},
|
|
63
|
+
"cell": {
|
|
64
|
+
"modules": {
|
|
65
|
+
"backend": [
|
|
66
|
+
"lib/node/module"
|
|
67
|
+
]
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from './validation-pipe';
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { describe, it } from 'bun:test';
|
|
2
|
+
import { expect } from 'chai';
|
|
3
|
+
import { IsInt, IsOptional, IsString, Min } from 'class-validator';
|
|
4
|
+
import { IncomingMessage, ServerResponse } from 'node:http';
|
|
5
|
+
import { Socket } from 'node:net';
|
|
6
|
+
import { ValidationErrors } from '@celljs/web';
|
|
7
|
+
import { ValidationPipe, ValidationOptions } from './validation-pipe';
|
|
8
|
+
|
|
9
|
+
class CreateUser {
|
|
10
|
+
@IsString()
|
|
11
|
+
name: string;
|
|
12
|
+
|
|
13
|
+
@IsOptional()
|
|
14
|
+
@IsInt()
|
|
15
|
+
@Min(0)
|
|
16
|
+
age?: number;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
class Cookies {
|
|
20
|
+
constructor(protected readonly values: Record<string, string>) { }
|
|
21
|
+
|
|
22
|
+
get(name: string): string | undefined {
|
|
23
|
+
return this.values[name];
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function createPipe(options: ValidationOptions = { detailedOutputDisabled: false, transformEnabled: true }): ValidationPipe {
|
|
28
|
+
const pipe = new ValidationPipe();
|
|
29
|
+
(pipe as any).options = options;
|
|
30
|
+
return pipe;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
describe('ValidationPipe', () => {
|
|
34
|
+
|
|
35
|
+
it('passes the request and response through, whatever the parameter type', async () => {
|
|
36
|
+
const pipe = createPipe();
|
|
37
|
+
const request = new IncomingMessage(new Socket());
|
|
38
|
+
const response = new ServerResponse(request);
|
|
39
|
+
expect(await pipe.transform(response, { argType: Object })).to.equal(response);
|
|
40
|
+
expect(await pipe.transform(response, { argType: ServerResponse })).to.equal(response);
|
|
41
|
+
expect(await pipe.transform(request, { argType: CreateUser })).to.equal(request);
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
it('keeps other framework objects with their methods', async () => {
|
|
45
|
+
const cookies = new Cookies({ token: 'abc' });
|
|
46
|
+
const result = await createPipe().transform(cookies, { argType: CreateUser });
|
|
47
|
+
expect(result).to.equal(cookies);
|
|
48
|
+
expect(result.get('token')).to.equal('abc');
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
it('turns request data into the parameter class and validates it', async () => {
|
|
52
|
+
const pipe = createPipe();
|
|
53
|
+
const user = await pipe.transform({ name: 'Tom', age: 3 }, { argType: CreateUser });
|
|
54
|
+
expect(user).to.be.instanceOf(CreateUser);
|
|
55
|
+
expect(user.name).to.equal('Tom');
|
|
56
|
+
const error = await pipe.transform({ name: 1, age: -1 }, { argType: CreateUser }).catch(e => e) as ValidationErrors;
|
|
57
|
+
expect(error).to.be.instanceOf(ValidationErrors);
|
|
58
|
+
expect(error.errors?.map(e => e.property)).to.deep.equal(['name', 'age']);
|
|
59
|
+
expect(error.errors?.[0].constraints).to.have.property('isString');
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
it('answers without the errors when detailedOutputDisabled is set', async () => {
|
|
63
|
+
const error = await createPipe({ detailedOutputDisabled: true }).transform({ name: 1 }, { argType: CreateUser }).catch(e => e) as ValidationErrors;
|
|
64
|
+
expect(error).to.be.instanceOf(ValidationErrors);
|
|
65
|
+
expect(error.errors).to.equal(undefined);
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
it('hands back the request data when transformEnabled is false', async () => {
|
|
69
|
+
const data = { name: 'Tom' };
|
|
70
|
+
expect(await createPipe({ transformEnabled: false }).transform(data, { argType: CreateUser })).to.equal(data);
|
|
71
|
+
// null is validated as {}: a required property fails.
|
|
72
|
+
expect(await createPipe({ transformEnabled: false }).transform(null, { argType: CreateUser }).catch(e => e)).to.be.instanceOf(ValidationErrors);
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
it('leaves primitive, Date, Object and Array parameters to the other pipes', async () => {
|
|
76
|
+
const pipe = createPipe();
|
|
77
|
+
const data = { a: { b: 1 } };
|
|
78
|
+
expect(await pipe.transform(data, { argType: Object })).to.equal(data);
|
|
79
|
+
expect(await pipe.transform([1, 2], { argType: Array })).to.deep.equal([1, 2]);
|
|
80
|
+
expect(await pipe.transform('5', { argType: Number })).to.equal('5');
|
|
81
|
+
expect(await pipe.transform('5', {})).to.equal('5');
|
|
82
|
+
});
|
|
83
|
+
});
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { Component, Value } from '@celljs/core';
|
|
2
|
+
import { ArgumentMetadata, PipeTransform, ValidationErrors } from '@celljs/web';
|
|
3
|
+
import { instanceToPlain, plainToInstance } from 'class-transformer';
|
|
4
|
+
import { validate } from 'class-validator';
|
|
5
|
+
|
|
6
|
+
/** `cell.validation`. */
|
|
7
|
+
export interface ValidationOptions {
|
|
8
|
+
/** Answer 400 without the errors. Default false. */
|
|
9
|
+
detailedOutputDisabled?: boolean;
|
|
10
|
+
/** Hand the method the instance of the parameter class; otherwise the request data it was made from. Default true. */
|
|
11
|
+
transformEnabled?: boolean;
|
|
12
|
+
/** Options of class-transformer's `plainToInstance` / `instanceToPlain`. */
|
|
13
|
+
transformOptions?: Record<string, unknown>;
|
|
14
|
+
/** Options of class-validator's `validate`. */
|
|
15
|
+
validatorOptions?: Record<string, unknown>;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** Types the pipe leaves to `TypeConversionPipe` of `@celljs/web` or passes as they are. */
|
|
19
|
+
const PLAIN_TYPES: Function[] = [String, Number, Boolean, Date, Object, Array];
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Turns request data into an instance of the parameter class with class-transformer and checks it with
|
|
23
|
+
* class-validator: `@Body() user: CreateUser` gets a `CreateUser` whose decorators (`@IsString()`...) hold,
|
|
24
|
+
* or the request answers 400 with the errors ({@link ValidationErrors}).
|
|
25
|
+
*/
|
|
26
|
+
@Component(PipeTransform)
|
|
27
|
+
export class ValidationPipe implements PipeTransform<any> {
|
|
28
|
+
|
|
29
|
+
@Value('cell.validation')
|
|
30
|
+
protected options?: ValidationOptions;
|
|
31
|
+
|
|
32
|
+
readonly priority = 900;
|
|
33
|
+
|
|
34
|
+
async transform(value: any, { argType }: ArgumentMetadata): Promise<any> {
|
|
35
|
+
if (!argType || PLAIN_TYPES.includes(argType) || !this.isData(value)) {
|
|
36
|
+
return value;
|
|
37
|
+
}
|
|
38
|
+
const opts = this.options || {};
|
|
39
|
+
const originalValue = value;
|
|
40
|
+
value = value === null ? {} : value;
|
|
41
|
+
const isNil = value !== originalValue;
|
|
42
|
+
const isPrimitive = this.isPrimitive(value);
|
|
43
|
+
this.stripProtoKeys(value);
|
|
44
|
+
let entity: any = plainToInstance(argType, value, opts.transformOptions);
|
|
45
|
+
const originalEntity = entity;
|
|
46
|
+
if (entity.constructor !== argType) {
|
|
47
|
+
if (isPrimitive) {
|
|
48
|
+
// Validate a primitive against the declared class, then hand back the primitive.
|
|
49
|
+
entity = { constructor: argType };
|
|
50
|
+
} else {
|
|
51
|
+
entity.constructor = argType;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
const errors = await validate(entity, opts.validatorOptions);
|
|
55
|
+
if (errors.length > 0) {
|
|
56
|
+
throw new ValidationErrors(opts.detailedOutputDisabled ? undefined : errors as any);
|
|
57
|
+
}
|
|
58
|
+
if (isPrimitive) {
|
|
59
|
+
entity = originalEntity;
|
|
60
|
+
}
|
|
61
|
+
if (opts.transformEnabled !== false) {
|
|
62
|
+
return entity;
|
|
63
|
+
}
|
|
64
|
+
if (isNil) {
|
|
65
|
+
return originalValue;
|
|
66
|
+
}
|
|
67
|
+
return opts.validatorOptions && Object.keys(opts.validatorOptions).length > 0
|
|
68
|
+
? instanceToPlain(entity, opts.transformOptions)
|
|
69
|
+
: value;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
private stripProtoKeys(value: Record<string, any>): void {
|
|
73
|
+
if (typeof value !== 'object') {
|
|
74
|
+
return;
|
|
75
|
+
}
|
|
76
|
+
delete value.__proto__;
|
|
77
|
+
for (const key of Object.keys(value)) {
|
|
78
|
+
if (typeof value[key] === 'object' && value[key]) {
|
|
79
|
+
this.stripProtoKeys(value[key]);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Request data: primitives, arrays and plain objects, as parsed from JSON, query strings or RPC
|
|
86
|
+
* messages. Objects the framework passes in (request, response, session, cookies, errors) are
|
|
87
|
+
* class instances and pass through: converting them would copy them property by property, which
|
|
88
|
+
* never ends for the circular request and response.
|
|
89
|
+
*/
|
|
90
|
+
private isData(value: unknown): boolean {
|
|
91
|
+
if (typeof value === 'function') {
|
|
92
|
+
return false;
|
|
93
|
+
}
|
|
94
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value)) {
|
|
95
|
+
return true;
|
|
96
|
+
}
|
|
97
|
+
const proto = Object.getPrototypeOf(value);
|
|
98
|
+
return proto === Object.prototype || proto === null;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
private isPrimitive(value: unknown): boolean {
|
|
102
|
+
return ['number', 'boolean', 'string'].indexOf(typeof value) !== -1;
|
|
103
|
+
}
|
|
104
|
+
}
|