koatty_validation 1.0.4 → 1.0.12

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/dist/util.js CHANGED
@@ -1,284 +1,17 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.IsHash = exports.IsUrl = exports.IsPhoneNumber = exports.IsIP = exports.IsEmail = exports.Length = exports.Max = exports.Min = exports.IsDate = exports.IsNotIn = exports.IsIn = exports.Contains = exports.NotEquals = exports.Equals = exports.IsNotEmpty = exports.IsPlateNumber = exports.IsMobile = exports.IsZipCode = exports.IsIdNumber = exports.IsCnName = exports.IsDefined = exports.Expose = exports.setExpose = exports.ValidatorFuncs = exports.FunctionValidator = exports.ClassValidator = void 0;
3
+ exports.plateNumber = exports.zipCode = exports.mobile = exports.idNumber = exports.cnName = exports.checkParamsType = exports.convertParamsType = exports.convertDtoParamsType = exports.plainToClass = exports.getOriginMetadata = exports.defineNewProperty = exports.recursiveGetMetadata = exports.setExpose = void 0;
4
4
  const tslib_1 = require("tslib");
5
5
  /**
6
6
  * @ author: richen
7
7
  * @ copyright: Copyright (c) - <richenlin(at)gmail.com>
8
8
  * @ license: MIT
9
- * @ version: 2020-05-10 10:45:21
9
+ * @ version: 2020-03-20 11:34:38
10
10
  */
11
- const helper = tslib_1.__importStar(require("koatty_lib"));
12
- const lib_1 = require("./lib");
13
- const class_validator_1 = require("class-validator");
14
- class ValidateClass {
15
- constructor() {
16
- }
17
- /**
18
- *
19
- *
20
- * @static
21
- * @returns
22
- * @memberof ValidateUtil
23
- */
24
- static getInstance() {
25
- return this.instance || (this.instance = new ValidateClass());
26
- }
27
- /**
28
- * validated data vs dto class
29
- *
30
- * @param {*} Clazz
31
- * @param {*} data
32
- * @param {boolean} [convert=false] auto convert parameters type
33
- * @returns {Promise<any>}
34
- * @memberof ValidateClass
35
- */
36
- async valid(Clazz, data, convert = false) {
37
- let obj = {};
38
- if (data instanceof Clazz) {
39
- obj = data;
40
- }
41
- else {
42
- obj = lib_1.plainToClass(Clazz, data, convert);
43
- }
44
- let errors = [];
45
- if (convert) {
46
- errors = await class_validator_1.validate(obj);
47
- }
48
- else {
49
- errors = await class_validator_1.validate(obj, { skipMissingProperties: true });
50
- }
51
- if (errors.length > 0) {
52
- const err = new Error(Object.values(errors[0].constraints)[0]);
53
- err.code = 400;
54
- err.status = 400;
55
- throw err;
56
- }
57
- return obj;
58
- }
59
- }
60
- /**
61
- * ClassValidator for manual
62
- */
63
- exports.ClassValidator = ValidateClass.getInstance();
64
- /**
65
- * Validator Functions
66
- */
67
- exports.FunctionValidator = {
68
- /**
69
- * Checks if value matches ("===") the comparison.
70
- */
71
- Equals: (value, comparison) => {
72
- return class_validator_1.equals(value, comparison);
73
- },
74
- /**
75
- * Checks if value does not match ("!==") the comparison.
76
- */
77
- NotEquals: (value, comparison) => {
78
- return class_validator_1.notEquals(value, comparison);
79
- },
80
- /**
81
- * Checks if the string contains the seed. If given value is not a string, then it returns false.
82
- */
83
- Contains: (value, seed) => {
84
- return class_validator_1.contains(value, seed);
85
- },
86
- /**
87
- * Checks if given value is in a array of allowed values.
88
- */
89
- IsIn: (value, possibleValues) => {
90
- return class_validator_1.isIn(value, possibleValues);
91
- },
92
- /**
93
- * Checks if given value not in a array of allowed values.
94
- */
95
- IsNotIn: (value, possibleValues) => {
96
- return class_validator_1.isNotIn(value, possibleValues);
97
- },
98
- /**
99
- * Checks if a given value is a real date.
100
- */
101
- IsDate: (value) => {
102
- return class_validator_1.isDate(value);
103
- },
104
- /**
105
- * Checks if the first number is greater than or equal to the second.
106
- */
107
- Min: (num, min) => {
108
- return helper.toNumber(num) >= min;
109
- },
110
- /**
111
- * Checks if the first number is less than or equal to the second.
112
- */
113
- Max: (num, max) => {
114
- return helper.toNumber(num) <= max;
115
- },
116
- /**
117
- * Checks if the string's length falls in a range. Note: this function takes into account surrogate pairs.
118
- * If given value is not a string, then it returns false.
119
- */
120
- Length: (value, min, max) => {
121
- return class_validator_1.length(value, min, max);
122
- },
123
- /**
124
- * Checks if the string is an email. If given value is not a string, then it returns false.
125
- */
126
- IsEmail: (value, options) => {
127
- return class_validator_1.isEmail(value, options);
128
- },
129
- /**
130
- * Checks if the string is an IP (version 4 or 6). If given value is not a string, then it returns false.
131
- */
132
- IsIP: (value, version) => {
133
- return class_validator_1.isIP(value, version);
134
- },
135
- /**
136
- * Checks if the string is a valid phone number.
137
- * @param value — the potential phone number string to test
138
- * @param region 2 characters uppercase country code (e.g. DE, US, CH). If users must enter the intl.
139
- * prefix (e.g. +41), then you may pass "ZZ" or null as region.
140
- * See [google-libphonenumber, metadata.js:countryCodeToRegionCodeMap on github]
141
- * {@link https://github.com/ruimarinho/google-libphonenumber/blob/1e46138878cff479aafe2ce62175c6c49cb58720/src/metadata.js#L33}
142
- */
143
- IsPhoneNumber: (value, region) => {
144
- return class_validator_1.isPhoneNumber(value, region);
145
- },
146
- /**
147
- * Checks if the string is an url. If given value is not a string, then it returns false.
148
- */
149
- IsUrl: (value, options) => {
150
- return class_validator_1.isURL(value, options);
151
- },
152
- /**
153
- * check if the string is a hash of type algorithm. Algorithm is one of
154
- * ['md4', 'md5', 'sha1', 'sha256', 'sha384', 'sha512', 'ripemd128', 'ripemd160', 'tiger128', 'tiger160', 'tiger192', 'crc32', 'crc32b']
155
- */
156
- IsHash: (value, algorithm) => {
157
- return class_validator_1.isHash(value, algorithm);
158
- },
159
- /**
160
- * Checks if value is a chinese name.
161
- */
162
- IsCnName: (value) => {
163
- if (!helper.isString(value)) {
164
- return false;
165
- }
166
- return lib_1.cnName(value);
167
- },
168
- /**
169
- * Checks if value is a idcard number.
170
- */
171
- IsIdNumber: (value) => {
172
- if (!helper.isString(value)) {
173
- return false;
174
- }
175
- return lib_1.idNumber(value);
176
- },
177
- /**
178
- * Checks if value is a zipCode.
179
- */
180
- IsZipCode: (value) => {
181
- if (!helper.isString(value)) {
182
- return false;
183
- }
184
- return lib_1.zipCode(value);
185
- },
186
- /**
187
- * Checks if value is a mobile phone number.
188
- */
189
- IsMobile: (value) => {
190
- if (!helper.isString(value)) {
191
- return false;
192
- }
193
- return lib_1.mobile(value);
194
- },
195
- /**
196
- * Checks if value is a plateNumber.
197
- */
198
- IsPlateNumber: (value) => {
199
- if (!helper.isString(value)) {
200
- return false;
201
- }
202
- return lib_1.plateNumber(value);
203
- },
204
- /**
205
- * Checks value is not empty, undefined, null, '', NaN, [], {} and any empty string(including spaces,
206
- * tabs, formfeeds, etc.), returns false
207
- */
208
- IsNotEmpty: (value) => {
209
- return !helper.isEmpty(value);
210
- }
211
- };
212
- /**
213
- * Use functions or built-in rules for validation.
214
- *
215
- * @export
216
- * @param {string} name
217
- * @param {*} value
218
- * @param {string} type
219
- * @param {(ValidRules | ValidRules[] | Function)} rule
220
- * @param {string} [message]
221
- * @param {boolean} [checkType=true]
222
- * @returns
223
- */
224
- function ValidatorFuncs(name, value, type, rule, message, checkType = true) {
225
- // check type
226
- if (checkType && !lib_1.checkParamsType(value, type)) {
227
- const err = new Error(`TypeError: invalid arguments '${name}'.`);
228
- err.code = 400;
229
- err.status = 400;
230
- throw err;
231
- }
232
- if (helper.isFunction(rule)) {
233
- if (!rule(value)) {
234
- const err = new Error(message || `ValidatorError: invalid arguments[${name}].`);
235
- err.code = 400;
236
- err.status = 400;
237
- throw err;
238
- }
239
- return value;
240
- }
241
- else {
242
- const funcs = rule;
243
- if (helper.isString(rule)) {
244
- funcs.push(rule);
245
- }
246
- if (funcs.some((it) => exports.FunctionValidator[it] && !exports.FunctionValidator[it](value))) {
247
- const err = new Error(message || `ValidatorError: invalid arguments[${name}].`);
248
- err.code = 400;
249
- err.status = 400;
250
- throw err;
251
- }
252
- }
253
- return value;
254
- }
255
- exports.ValidatorFuncs = ValidatorFuncs;
256
- /**
257
- * append to the target class method to validated parameter.
258
- *
259
- * @export
260
- * @param {*} target
261
- * @param {string} propertyKey
262
- */
263
- // export function validParamter(target: any, propertyKey: string, metaDataTypes: any[]) {
264
- // const validMetaDatas = recursiveGetMetadata(PARAM_RULE_KEY, target, propertyKey);
265
- // defineNewProperty(target, propertyKey, function (props: any[]) {
266
- // //convert type
267
- // props = props.map((v, k) => {
268
- // if (helper.isString(metaDataTypes[k])) {
269
- // v = convertParamsType(v, metaDataTypes[k]);
270
- // //@Valid()
271
- // if (validMetaDatas[k] && validMetaDatas[k].type && validMetaDatas[k].rule) {
272
- // ValidatorFuncs(`${k}`, v, validMetaDatas[k].type, validMetaDatas[k].rule, validMetaDatas[k].message);
273
- // }
274
- // } else if (helper.isClass(metaDataTypes[k])) {
275
- // v = plainToClass(metaDataTypes[k], v, true);
276
- // }
277
- // return v;
278
- // });
279
- // return props;
280
- // });
281
- // }
11
+ // tslint:disable-next-line: no-import-side-effect
12
+ require("reflect-metadata");
13
+ const helper = (0, tslib_1.__importStar)(require("koatty_lib"));
14
+ const rule_1 = require("./rule");
282
15
  /**
283
16
  * Set property as included in the process of transformation.
284
17
  *
@@ -289,602 +22,401 @@ exports.ValidatorFuncs = ValidatorFuncs;
289
22
  function setExpose(object, propertyName) {
290
23
  const types = Reflect.getMetadata("design:type", object, propertyName);
291
24
  if (types) {
292
- const originMap = lib_1.getOriginMetadata(lib_1.PARAM_TYPE_KEY, object);
25
+ const originMap = getOriginMetadata(rule_1.PARAM_TYPE_KEY, object);
293
26
  originMap.set(propertyName, types.name);
294
27
  }
295
28
  }
296
29
  exports.setExpose = setExpose;
297
- /**
298
- * Marks property as included in the process of transformation.
299
- *
300
- * @export
301
- * @returns {PropertyDecorator}
302
- */
303
- function Expose() {
304
- return function (object, propertyName) {
305
- const types = Reflect.getMetadata("design:type", object, propertyName);
306
- if (types) {
307
- const originMap = lib_1.getOriginMetadata(lib_1.PARAM_TYPE_KEY, object);
308
- originMap.set(propertyName, types.name);
309
- }
310
- };
30
+ const functionPrototype = Object.getPrototypeOf(Function);
31
+ // get property of an object
32
+ // https://tc39.github.io/ecma262/#sec-ordinarygetprototypeof
33
+ function ordinaryGetPrototypeOf(obj) {
34
+ const proto = Object.getPrototypeOf(obj);
35
+ if (typeof obj !== "function" || obj === functionPrototype) {
36
+ return proto;
37
+ }
38
+ // TypeScript doesn't set __proto__ in ES5, as it's non-standard.
39
+ // Try to determine the superclass constructor. Compatible implementations
40
+ // must either set __proto__ on a subclass constructor to the superclass constructor,
41
+ // or ensure each class has a valid `constructor` property on its prototype that
42
+ // points back to the constructor.
43
+ // If this is not the same as Function.[[Prototype]], then this is definitely inherited.
44
+ // This is the case when in ES6 or when using __proto__ in a compatible browser.
45
+ if (proto !== functionPrototype) {
46
+ return proto;
47
+ }
48
+ // If the super prototype is Object.prototype, null, or undefined, then we cannot determine the heritage.
49
+ const prototype = obj.prototype;
50
+ const prototypeProto = prototype && Object.getPrototypeOf(prototype);
51
+ // tslint:disable-next-line: triple-equals
52
+ if (prototypeProto == undefined || prototypeProto === Object.prototype) {
53
+ return proto;
54
+ }
55
+ // If the constructor was not a function, then we cannot determine the heritage.
56
+ const constructor = prototypeProto.constructor;
57
+ if (typeof constructor !== "function") {
58
+ return proto;
59
+ }
60
+ // If we have some kind of self-reference, then we cannot determine the heritage.
61
+ if (constructor === obj) {
62
+ return proto;
63
+ }
64
+ // we have a pretty good guess at the heritage.
65
+ return constructor;
311
66
  }
312
- exports.Expose = Expose;
313
67
  /**
314
- * Identifies that the field needs to be defined
68
+ * get property metadata data
315
69
  *
316
- * @export
317
- * @returns {PropertyDecorator}
70
+ * @param {(string | symbol)} decoratorNameKey
71
+ * @param {*} target
72
+ * @returns
318
73
  */
319
- function IsDefined() {
320
- return function (object, propertyName) {
321
- setExpose(object, propertyName);
322
- };
74
+ function listPropertyData(decoratorNameKey, target, propertyKey) {
75
+ const originMap = getOriginMetadata(decoratorNameKey, target, propertyKey);
76
+ const data = {};
77
+ for (const [key, value] of originMap) {
78
+ data[key] = value;
79
+ }
80
+ return data;
323
81
  }
324
- exports.IsDefined = IsDefined;
325
82
  /**
326
- * Checks if value is a chinese name.
327
- *
328
- * @export
329
- * @param {string} property
330
- * @param {ValidationOptions} [validationOptions]
331
- * @returns {PropertyDecorator}
83
+ * get metadata value of a metadata key on the prototype chain of an object and property
84
+ * @param metadataKey metadata key
85
+ * @param target the target of metadataKey
332
86
  */
333
- function IsCnName(validationOptions) {
334
- return function (object, propertyName) {
335
- setExpose(object, propertyName);
336
- class_validator_1.registerDecorator({
337
- name: "IsCnName",
338
- target: object.constructor,
339
- propertyName,
340
- options: validationOptions,
341
- validator: {
342
- validate(value, args) {
343
- return lib_1.cnName(value);
344
- },
345
- defaultMessage(args) {
346
- return "invalid parameter ($property).";
87
+ function recursiveGetMetadata(metadataKey, target, propertyKey) {
88
+ // get metadata value of a metadata key on the prototype
89
+ // let metadata = Reflect.getOwnMetadata(metadataKey, target, propertyKey);
90
+ const metadata = listPropertyData(metadataKey, target, propertyKey) || {};
91
+ // get metadata value of a metadata key on the prototype chain
92
+ let parent = ordinaryGetPrototypeOf(target);
93
+ while (parent !== null) {
94
+ // metadata = Reflect.getOwnMetadata(metadataKey, parent, propertyKey);
95
+ const pMetadata = listPropertyData(metadataKey, parent, propertyKey);
96
+ if (pMetadata) {
97
+ for (const n in pMetadata) {
98
+ if (!metadata.hasOwnProperty(n)) {
99
+ metadata[n] = pMetadata[n];
347
100
  }
348
101
  }
349
- });
350
- };
102
+ }
103
+ parent = ordinaryGetPrototypeOf(parent);
104
+ }
105
+ return metadata;
351
106
  }
352
- exports.IsCnName = IsCnName;
107
+ exports.recursiveGetMetadata = recursiveGetMetadata;
353
108
  /**
354
- * Checks if value is a idCard number(chinese).
109
+ * Dynamically add methods for target class types
355
110
  *
356
- * @export
357
- * @param {string} property
358
- * @param {ValidationOptions} [validationOptions]
359
- * @returns {PropertyDecorator}
111
+ * @param {Function} clazz
112
+ * @param {string} protoName
113
+ * @param {Function} func
360
114
  */
361
- function IsIdNumber(validationOptions) {
362
- return function (object, propertyName) {
363
- setExpose(object, propertyName);
364
- class_validator_1.registerDecorator({
365
- name: "IsIdNumber",
366
- target: object.constructor,
367
- propertyName,
368
- options: validationOptions,
369
- validator: {
370
- validate(value, args) {
371
- return lib_1.idNumber(value);
372
- },
373
- defaultMessage(args) {
374
- return "invalid parameter ($property).";
375
- }
115
+ function defineNewProperty(clazz, protoName, func) {
116
+ const oldMethod = Reflect.get(clazz.prototype, protoName);
117
+ if (oldMethod) {
118
+ Reflect.defineProperty(clazz.prototype, protoName, {
119
+ writable: true,
120
+ value: function fn(...props) {
121
+ // process paramter
122
+ props = func(props);
123
+ // tslint:disable-next-line: no-invalid-this
124
+ return Reflect.apply(oldMethod, this, props);
376
125
  }
377
126
  });
378
- };
127
+ }
379
128
  }
380
- exports.IsIdNumber = IsIdNumber;
129
+ exports.defineNewProperty = defineNewProperty;
381
130
  /**
382
- * Checks if value is a zipCode(chinese).
383
131
  *
384
- * @export
385
- * @param {string} property
386
- * @param {ValidationOptions} [validationOptions]
387
- * @returns {PropertyDecorator}
388
- */
389
- function IsZipCode(validationOptions) {
390
- return function (object, propertyName) {
391
- setExpose(object, propertyName);
392
- class_validator_1.registerDecorator({
393
- name: "IsZipCode",
394
- target: object.constructor,
395
- propertyName,
396
- options: validationOptions,
397
- validator: {
398
- validate(value, args) {
399
- return lib_1.zipCode(value);
400
- },
401
- defaultMessage(args) {
402
- return "invalid parameter ($property).";
403
- }
404
- }
405
- });
406
- };
407
- }
408
- exports.IsZipCode = IsZipCode;
409
- /**
410
- * Checks if value is a mobile phone number(chinese).
411
132
  *
412
- * @export
413
- * @param {string} property
414
- * @param {ValidationOptions} [validationOptions]
415
- * @returns {PropertyDecorator}
133
+ * @param {(string | symbol)} metadataKey
134
+ * @param {*} target
135
+ * @param {(string | symbol)} [propertyKey]
136
+ * @returns
416
137
  */
417
- function IsMobile(validationOptions) {
418
- return function (object, propertyName) {
419
- setExpose(object, propertyName);
420
- class_validator_1.registerDecorator({
421
- name: "IsMobile",
422
- target: object.constructor,
423
- propertyName,
424
- options: validationOptions,
425
- validator: {
426
- validate(value, args) {
427
- return lib_1.mobile(value);
428
- },
429
- defaultMessage(args) {
430
- return "invalid parameter ($property).";
431
- }
432
- }
433
- });
434
- };
138
+ function getOriginMetadata(metadataKey, target, propertyKey) {
139
+ // filter Object.create(null)
140
+ if (typeof target === "object" && target.constructor) {
141
+ target = target.constructor;
142
+ }
143
+ if (propertyKey) {
144
+ // for property or method
145
+ if (!Reflect.hasMetadata(metadataKey, target, propertyKey)) {
146
+ Reflect.defineMetadata(metadataKey, new Map(), target, propertyKey);
147
+ }
148
+ return Reflect.getMetadata(metadataKey, target, propertyKey);
149
+ }
150
+ else {
151
+ // for class
152
+ if (!Reflect.hasMetadata(metadataKey, target)) {
153
+ Reflect.defineMetadata(metadataKey, new Map(), target);
154
+ }
155
+ return Reflect.getMetadata(metadataKey, target);
156
+ }
435
157
  }
436
- exports.IsMobile = IsMobile;
158
+ exports.getOriginMetadata = getOriginMetadata;
437
159
  /**
438
- * Checks if value is a plate number(chinese).
439
160
  *
440
- * @export
441
- * @param {string} property
442
- * @param {ValidationOptions} [validationOptions]
443
- * @returns {PropertyDecorator}
444
- */
445
- function IsPlateNumber(validationOptions) {
446
- return function (object, propertyName) {
447
- setExpose(object, propertyName);
448
- class_validator_1.registerDecorator({
449
- name: "IsPlateNumber",
450
- target: object.constructor,
451
- propertyName,
452
- options: validationOptions,
453
- validator: {
454
- validate(value, args) {
455
- return lib_1.plateNumber(value);
456
- },
457
- defaultMessage(args) {
458
- return "invalid parameter ($property).";
459
- }
460
- }
461
- });
462
- };
463
- }
464
- exports.IsPlateNumber = IsPlateNumber;
465
- /**
466
- * Checks value is not empty, undefined, null, '', NaN, [], {} and any empty string(including spaces, tabs, formfeeds, etc.), returns false.
467
161
  *
468
162
  * @export
469
- * @param {ValidationOptions} [validationOptions]
470
- * @returns {PropertyDecorator}
163
+ * @param {*} clazz
164
+ * @param {*} data
165
+ * @param {boolean} [convert=false]
166
+ * @returns
471
167
  */
472
- function IsNotEmpty(validationOptions) {
473
- return function (object, propertyName) {
474
- setExpose(object, propertyName);
475
- class_validator_1.registerDecorator({
476
- name: "IsNotEmpty",
477
- target: object.constructor,
478
- propertyName,
479
- options: validationOptions,
480
- validator: {
481
- validate(value, args) {
482
- return !helper.isEmpty(value);
483
- },
484
- defaultMessage(args) {
485
- return "invalid parameter ($property).";
486
- }
487
- }
488
- });
489
- };
168
+ function plainToClass(clazz, data, convert = false) {
169
+ if (helper.isClass(clazz)) {
170
+ let cls;
171
+ if (!helper.isObject(data)) {
172
+ data = {};
173
+ }
174
+ if (data instanceof clazz) {
175
+ cls = data;
176
+ }
177
+ else {
178
+ cls = Reflect.construct(clazz, []);
179
+ }
180
+ if (convert) {
181
+ return convertDtoParamsType(clazz, cls, data);
182
+ }
183
+ return Object.assign(cls, data);
184
+ }
185
+ return data;
490
186
  }
491
- exports.IsNotEmpty = IsNotEmpty;
187
+ exports.plainToClass = plainToClass;
492
188
  /**
493
- * Checks if value matches ("===") the comparison.
189
+ * convertDtoParamsType
494
190
  *
495
- * @export
496
- * @param {*} comparison
497
- * @param {ValidationOptions} [validationOptions]
498
- * @returns {PropertyDecorator}
191
+ * @param {*} clazz
192
+ * @param {*} cls
193
+ * @param {*} data
194
+ * @returns {*}
499
195
  */
500
- function Equals(comparison, validationOptions) {
501
- return function (object, propertyName) {
502
- setExpose(object, propertyName);
503
- class_validator_1.registerDecorator({
504
- name: "vEquals",
505
- target: object.constructor,
506
- propertyName,
507
- options: validationOptions,
508
- validator: {
509
- validate(value, args) {
510
- return class_validator_1.equals(value, comparison);
511
- },
512
- defaultMessage(args) {
513
- return `invalid parameter, ($property) must be equals ${comparison}.`;
514
- }
196
+ function convertDtoParamsType(clazz, cls, data) {
197
+ if (Object.prototype.hasOwnProperty.call(cls, "_typeDef")) {
198
+ for (const key in cls) {
199
+ if (Object.prototype.hasOwnProperty.call(data, key)
200
+ && Object.prototype.hasOwnProperty.call(cls._typeDef, key)) {
201
+ data[key] = convertParamsType(data[key], cls._typeDef[key]);
515
202
  }
516
- });
517
- };
518
- }
519
- exports.Equals = Equals;
520
- /**
521
- * Checks if value does not match ("!==") the comparison.
522
- *
523
- * @export
524
- * @param {*} comparison
525
- * @param {ValidationOptions} [validationOptions]
526
- * @returns {PropertyDecorator}
527
- */
528
- function NotEquals(comparison, validationOptions) {
529
- return function (object, propertyName) {
530
- setExpose(object, propertyName);
531
- class_validator_1.registerDecorator({
532
- name: "vNotEquals",
533
- target: object.constructor,
534
- propertyName,
535
- options: validationOptions,
536
- validator: {
537
- validate(value, args) {
538
- return class_validator_1.notEquals(value, comparison);
539
- },
540
- defaultMessage(args) {
541
- return `invalid parameter, ($property) must be not equals ${comparison}.`;
542
- }
203
+ }
204
+ }
205
+ else {
206
+ const originMap = getOriginMetadata(rule_1.PARAM_TYPE_KEY, clazz);
207
+ for (const [key, type] of originMap) {
208
+ if (key && Object.prototype.hasOwnProperty.call(data, key)) {
209
+ cls[key] = convertParamsType(data[key], type);
543
210
  }
544
- });
545
- };
211
+ }
212
+ }
213
+ return cls;
546
214
  }
547
- exports.NotEquals = NotEquals;
215
+ exports.convertDtoParamsType = convertDtoParamsType;
548
216
  /**
549
- * Checks if the string contains the seed.
217
+ * 绑定参数类型转换
550
218
  *
551
- * @export
552
- * @param {string} seed
553
- * @param {ValidationOptions} [validationOptions]
554
- * @returns {PropertyDecorator}
219
+ * @param {*} param
220
+ * @param {string} type
221
+ * @returns {*}
555
222
  */
556
- function Contains(seed, validationOptions) {
557
- return function (object, propertyName) {
558
- setExpose(object, propertyName);
559
- class_validator_1.registerDecorator({
560
- name: "vContains",
561
- target: object.constructor,
562
- propertyName,
563
- options: validationOptions,
564
- validator: {
565
- validate(value, args) {
566
- return class_validator_1.contains(value, seed);
567
- // return typeof value === "string" && (value.indexOf(seed) > -1);
568
- },
569
- defaultMessage(args) {
570
- return `invalid parameter, ($property) must be contains ${seed}.`;
223
+ function convertParamsType(param, type) {
224
+ try {
225
+ switch (type) {
226
+ case "Number":
227
+ case "number":
228
+ if (helper.isNaN(param)) {
229
+ return NaN;
571
230
  }
572
- }
573
- });
574
- };
575
- }
576
- exports.Contains = Contains;
577
- /**
578
- * Checks if given value is in a array of allowed values.
579
- *
580
- * @export
581
- * @param {any[]} possibleValues
582
- * @param {ValidationOptions} [validationOptions]
583
- * @returns {PropertyDecorator}
584
- */
585
- function IsIn(possibleValues, validationOptions) {
586
- return function (object, propertyName) {
587
- setExpose(object, propertyName);
588
- class_validator_1.registerDecorator({
589
- name: "vIsIn",
590
- target: object.constructor,
591
- propertyName,
592
- options: validationOptions,
593
- validator: {
594
- validate(value, args) {
595
- return class_validator_1.isIn(value, possibleValues);
596
- },
597
- defaultMessage(args) {
598
- return `invalid parameter ($property).`;
231
+ if (helper.isNumber(param)) {
232
+ return param;
599
233
  }
600
- }
601
- });
602
- };
603
- }
604
- exports.IsIn = IsIn;
605
- /**
606
- * Checks if given value not in a array of allowed values.
607
- *
608
- * @export
609
- * @param {any[]} possibleValues
610
- * @param {ValidationOptions} [validationOptions]
611
- * @returns {PropertyDecorator}
612
- */
613
- function IsNotIn(possibleValues, validationOptions) {
614
- return function (object, propertyName) {
615
- setExpose(object, propertyName);
616
- class_validator_1.registerDecorator({
617
- name: "vIsNotIn",
618
- target: object.constructor,
619
- propertyName,
620
- options: validationOptions,
621
- validator: {
622
- validate(value, args) {
623
- return class_validator_1.isNotIn(value, possibleValues);
624
- },
625
- defaultMessage(args) {
626
- return `invalid parameter ($property).`;
234
+ if (helper.isNumberString(param)) {
235
+ return helper.toNumber(param);
627
236
  }
628
- }
629
- });
630
- };
631
- }
632
- exports.IsNotIn = IsNotIn;
633
- /**
634
- * Checks if a given value is a real date.
635
- *
636
- * @export
637
- * @param {ValidationOptions} [validationOptions]
638
- * @returns {PropertyDecorator}
639
- */
640
- function IsDate(validationOptions) {
641
- return function (object, propertyName) {
642
- setExpose(object, propertyName);
643
- class_validator_1.registerDecorator({
644
- name: "vIsDate",
645
- target: object.constructor,
646
- propertyName,
647
- options: validationOptions,
648
- validator: {
649
- validate(value, args) {
650
- return class_validator_1.isDate(value);
651
- },
652
- defaultMessage(args) {
653
- return `invalid parameter ($property).`;
237
+ return NaN;
238
+ case "Boolean":
239
+ case "boolean":
240
+ return !!param;
241
+ case "Array":
242
+ case "array":
243
+ case "Tuple":
244
+ case "tuple":
245
+ if (helper.isArray(param)) {
246
+ return param;
654
247
  }
655
- }
656
- });
657
- };
658
- }
659
- exports.IsDate = IsDate;
660
- /**
661
- * Checks if the first number is greater than or equal to the min value.
662
- *
663
- * @export
664
- * @param {number} min
665
- * @param {ValidationOptions} [validationOptions]
666
- * @returns {PropertyDecorator}
667
- */
668
- function Min(min, validationOptions) {
669
- return function (object, propertyName) {
670
- setExpose(object, propertyName);
671
- class_validator_1.registerDecorator({
672
- name: "vMin",
673
- target: object.constructor,
674
- propertyName,
675
- options: validationOptions,
676
- validator: {
677
- validate(value, args) {
678
- return helper.toNumber(value) >= min;
679
- },
680
- defaultMessage(args) {
681
- return `invalid parameter ($property).`;
248
+ return helper.toArray(param);
249
+ case "String":
250
+ case "string":
251
+ if (helper.isString(param)) {
252
+ return param;
682
253
  }
683
- }
684
- });
685
- };
686
- }
687
- exports.Min = Min;
688
- /**
689
- * Checks if the first number is less than or equal to the max value.
690
- *
691
- * @export
692
- * @param {number} max
693
- * @param {ValidationOptions} [validationOptions]
694
- * @returns {PropertyDecorator}
695
- */
696
- function Max(max, validationOptions) {
697
- return function (object, propertyName) {
698
- setExpose(object, propertyName);
699
- class_validator_1.registerDecorator({
700
- name: "vMax",
701
- target: object.constructor,
702
- propertyName,
703
- options: validationOptions,
704
- validator: {
705
- validate(value, args) {
706
- return helper.toNumber(value) <= max;
707
- },
708
- defaultMessage(args) {
709
- return `invalid parameter ($property).`;
254
+ return helper.toString(param);
255
+ case "Null":
256
+ case "null":
257
+ return null;
258
+ case "Undefined":
259
+ case "undefined":
260
+ return undefined;
261
+ case "Bigint":
262
+ case "bigint":
263
+ if (typeof param === 'bigint') {
264
+ return param;
710
265
  }
711
- }
712
- });
713
- };
266
+ return BigInt(param);
267
+ // case "object":
268
+ // case "enum":
269
+ default: //any
270
+ return param;
271
+ }
272
+ }
273
+ catch (err) {
274
+ return param;
275
+ }
714
276
  }
715
- exports.Max = Max;
277
+ exports.convertParamsType = convertParamsType;
716
278
  /**
717
- * Checks if the string's length falls in a range. Note: this function takes into account surrogate pairs.
718
- * If given value is not a string, then it returns false.
279
+ * Check the base types.
719
280
  *
720
- * @export
721
- * @param {number} min
722
- * @param {number} [max]
723
- * @param {ValidationOptions} [validationOptions]
724
- * @returns {PropertyDecorator}
281
+ * @param {*} value
282
+ * @param {string} type
283
+ * @returns {*}
725
284
  */
726
- function Length(min, max, validationOptions) {
727
- return function (object, propertyName) {
728
- setExpose(object, propertyName);
729
- class_validator_1.registerDecorator({
730
- name: "vLength",
731
- target: object.constructor,
732
- propertyName,
733
- options: validationOptions,
734
- validator: {
735
- validate(value, args) {
736
- return class_validator_1.length(value, min, max);
737
- },
738
- defaultMessage(args) {
739
- return `invalid parameter ($property).`;
740
- }
285
+ function checkParamsType(value, type) {
286
+ switch (type) {
287
+ case "Number":
288
+ case "number":
289
+ if (!helper.isNumber(value) || helper.isNaN(value)) {
290
+ return false;
741
291
  }
742
- });
743
- };
292
+ return true;
293
+ case "Boolean":
294
+ case "boolean":
295
+ if (!helper.isBoolean(value)) {
296
+ return false;
297
+ }
298
+ return true;
299
+ case "Array":
300
+ case "array":
301
+ case "Tuple":
302
+ case "tuple":
303
+ if (!helper.isArray(value)) {
304
+ return false;
305
+ }
306
+ return true;
307
+ case "String":
308
+ case "string":
309
+ if (!helper.isString(value)) {
310
+ return false;
311
+ }
312
+ return true;
313
+ case "Object":
314
+ case "object":
315
+ case "Enum":
316
+ case "enum":
317
+ if (helper.isTrueEmpty(value)) {
318
+ return false;
319
+ }
320
+ return true;
321
+ case "Null":
322
+ case "null":
323
+ if (!helper.isNull(value)) {
324
+ return false;
325
+ }
326
+ return true;
327
+ case "Undefined":
328
+ case "undefined":
329
+ if (!helper.isUndefined(value)) {
330
+ return false;
331
+ }
332
+ return true;
333
+ case "Bigint":
334
+ case "bigint":
335
+ if (typeof value !== 'bigint') {
336
+ return false;
337
+ }
338
+ return true;
339
+ default: //any
340
+ return true;
341
+ }
744
342
  }
745
- exports.Length = Length;
343
+ exports.checkParamsType = checkParamsType;
746
344
  /**
747
- * Checks if the string is an email. If given value is not a string, then it returns false.
345
+ * Checks if value is a chinese name.
748
346
  *
749
- * @export
750
- * @param {IsEmailOptions} [options]
751
- * @param {ValidationOptions} [validationOptions]
752
- * @returns {PropertyDecorator}
347
+ * @param {string} value
348
+ * @returns {boolean}
753
349
  */
754
- function IsEmail(options, validationOptions) {
755
- return function (object, propertyName) {
756
- setExpose(object, propertyName);
757
- class_validator_1.registerDecorator({
758
- name: "vIsEmail",
759
- target: object.constructor,
760
- propertyName,
761
- options: validationOptions,
762
- validator: {
763
- validate(value, args) {
764
- return class_validator_1.isEmail(value);
765
- },
766
- defaultMessage(args) {
767
- return `invalid parameter ($property).`;
768
- }
769
- }
770
- });
771
- };
350
+ function cnName(value) {
351
+ const reg = /^([a-zA-Z0-9\u4e00-\u9fa5\·]{1,10})$/;
352
+ return reg.test(value);
772
353
  }
773
- exports.IsEmail = IsEmail;
354
+ exports.cnName = cnName;
774
355
  /**
775
- * Checks if the string is an IP (version 4 or 6). If given value is not a string, then it returns false.
356
+ * Checks if value is a idCard number.
776
357
  *
777
- * @export
778
- * @param {number} [version]
779
- * @param {ValidationOptions} [validationOptions]
780
- * @returns {PropertyDecorator}
358
+ * @param {string} value
359
+ * @returns
781
360
  */
782
- function IsIP(version, validationOptions) {
783
- return function (object, propertyName) {
784
- setExpose(object, propertyName);
785
- class_validator_1.registerDecorator({
786
- name: "vIsIP",
787
- target: object.constructor,
788
- propertyName,
789
- options: validationOptions,
790
- validator: {
791
- validate(value, args) {
792
- return class_validator_1.isIP(value, version);
793
- },
794
- defaultMessage(args) {
795
- return `invalid parameter ($property).`;
796
- }
797
- }
798
- });
799
- };
361
+ function idNumber(value) {
362
+ if (/^\d{15}$/.test(value)) {
363
+ return true;
364
+ }
365
+ if ((/^\d{17}[0-9X]$/).test(value)) {
366
+ const vs = '1,0,x,9,8,7,6,5,4,3,2'.split(',');
367
+ const ps = '7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2'.split(',');
368
+ const ss = value.toLowerCase().split('');
369
+ let r = 0;
370
+ for (let i = 0; i < 17; i++) {
371
+ r += ps[i] * ss[i];
372
+ }
373
+ const isOk = (vs[r % 11] === ss[17]);
374
+ return isOk;
375
+ }
376
+ return false;
800
377
  }
801
- exports.IsIP = IsIP;
378
+ exports.idNumber = idNumber;
802
379
  /**
803
- * Checks if the string is a valid phone number.
380
+ * Checks if value is a mobile phone number.
804
381
  *
805
- * @export
806
- * @param {string} {string} region 2 characters uppercase country code (e.g. DE, US, CH).
807
- * If users must enter the intl. prefix (e.g. +41), then you may pass "ZZ" or null as region.
808
- * See [google-libphonenumber, metadata.js:countryCodeToRegionCodeMap on github]
809
- * {@link https://github.com/ruimarinho/google-libphonenumber/blob/1e46138878cff479aafe2ce62175c6c49cb58720/src/metadata.js#L33}
810
- * @param {ValidationOptions} [validationOptions]
811
- * @returns {PropertyDecorator}
382
+ * @param {string} value
383
+ * @returns {boolean}
812
384
  */
813
- function IsPhoneNumber(region, validationOptions) {
814
- return function (object, propertyName) {
815
- setExpose(object, propertyName);
816
- class_validator_1.registerDecorator({
817
- name: "vIsPhoneNumber",
818
- target: object.constructor,
819
- propertyName,
820
- options: validationOptions,
821
- validator: {
822
- validate(value, args) {
823
- return class_validator_1.isPhoneNumber(value, region);
824
- },
825
- defaultMessage(args) {
826
- return `invalid parameter ($property).`;
827
- }
828
- }
829
- });
830
- };
385
+ function mobile(value) {
386
+ const reg = /^(13|14|15|16|17|18|19)\d{9}$/;
387
+ return reg.test(value);
831
388
  }
832
- exports.IsPhoneNumber = IsPhoneNumber;
389
+ exports.mobile = mobile;
833
390
  /**
834
- * Checks if the string is an url.
391
+ * Checks if value is a zipCode.
835
392
  *
836
- * @export
837
- * @param {IsURLOptions} [options]
838
- * @param {ValidationOptions} [validationOptions]
839
- * @returns {PropertyDecorator}
393
+ * @param {string} value
394
+ * @returns {boolean}
840
395
  */
841
- function IsUrl(options, validationOptions) {
842
- return function (object, propertyName) {
843
- setExpose(object, propertyName);
844
- class_validator_1.registerDecorator({
845
- name: "vIsUrl",
846
- target: object.constructor,
847
- propertyName,
848
- options: validationOptions,
849
- validator: {
850
- validate(value, args) {
851
- return class_validator_1.isURL(value, options);
852
- },
853
- defaultMessage(args) {
854
- return `invalid parameter ($property).`;
855
- }
856
- }
857
- });
858
- };
396
+ function zipCode(value) {
397
+ const reg = /^\d{6}$/;
398
+ return reg.test(value);
859
399
  }
860
- exports.IsUrl = IsUrl;
400
+ exports.zipCode = zipCode;
861
401
  /**
862
- * check if the string is a hash of type algorithm. Algorithm is one of ['md4', 'md5', 'sha1', 'sha256',
863
- * 'sha384', 'sha512', 'ripemd128', 'ripemd160', 'tiger128', 'tiger160', 'tiger192', 'crc32', 'crc32b']
402
+ * Checks if value is a plateNumber.
864
403
  *
865
- * @export
866
- * @param {HashAlgorithm} algorithm
867
- * @param {ValidationOptions} [validationOptions]
868
- * @returns {PropertyDecorator}
404
+ * @param {string} value
405
+ * @returns {boolean}
869
406
  */
870
- function IsHash(algorithm, validationOptions) {
871
- return function (object, propertyName) {
872
- setExpose(object, propertyName);
873
- class_validator_1.registerDecorator({
874
- name: "vIsHash",
875
- target: object.constructor,
876
- propertyName,
877
- options: validationOptions,
878
- validator: {
879
- validate(value, args) {
880
- return class_validator_1.isHash(value, algorithm);
881
- },
882
- defaultMessage(args) {
883
- return `invalid parameter, ($property) must be is an ${algorithm} Hash string.`;
884
- }
885
- }
886
- });
887
- };
407
+ function plateNumber(value) {
408
+ // let reg = new RegExp('^(([\u4e00-\u9fa5][a-zA-Z]|[\u4e00-\u9fa5]{2}\d{2}|[\u4e00-\u9fa5]{2}[a-zA-Z])[-]?|([wW][Jj][\u4e00-\u9fa5]{1}[-]?)|([a-zA-Z]{2}))([A-Za-z0-9]{5}|[DdFf][A-HJ-NP-Za-hj-np-z0-9][0-9]{4}|[0-9]{5}[DdFf])$');
409
+ // let xReg = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}(([0-9]{5}[DF]$)|([DF][A-HJ-NP-Z0-9][0-9]{4}$))/;
410
+ const xReg = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领]{1}[A-Z]{1}(([0-9]{5}[DF]$)|([DF][A-HJ-NP-Z0-9][0-9]{4}$))/;
411
+ // let cReg = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳]{1}$/;
412
+ const cReg = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领]{1}[A-Z]{1}[A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳]{1}$/;
413
+ if (value.length === 7) {
414
+ return cReg.test(value);
415
+ }
416
+ else {
417
+ //新能源车牌
418
+ return xReg.test(value);
419
+ }
888
420
  }
889
- exports.IsHash = IsHash;
421
+ exports.plateNumber = plateNumber;
890
422
  //# sourceMappingURL=util.js.map