koatty_validation 1.0.8 → 1.0.10

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,18 @@
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
+ // tslint:disable-next-line: no-import-side-effect
12
+ require("reflect-metadata");
11
13
  const helper = (0, 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 = (0, lib_1.plainToClass)(Clazz, data, convert);
43
- }
44
- let errors = [];
45
- if (convert) {
46
- errors = await (0, class_validator_1.validate)(obj);
47
- }
48
- else {
49
- errors = await (0, 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 (0, class_validator_1.equals)(value, comparison);
73
- },
74
- /**
75
- * Checks if value does not match ("!==") the comparison.
76
- */
77
- NotEquals: (value, comparison) => {
78
- return (0, 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 (0, 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 (0, 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 (0, class_validator_1.isNotIn)(value, possibleValues);
97
- },
98
- /**
99
- * Checks if a given value is a real date.
100
- */
101
- IsDate: (value) => {
102
- return (0, 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 (0, 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 (0, 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 (0, 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 (0, 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 (0, 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 (0, 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 (0, 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 (0, 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 (0, 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 (0, 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 (0, 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 && !(0, 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
- // }
14
+ const koatty_logger_1 = require("koatty_logger");
15
+ const rule_1 = require("./rule");
282
16
  /**
283
17
  * Set property as included in the process of transformation.
284
18
  *
@@ -289,602 +23,397 @@ exports.ValidatorFuncs = ValidatorFuncs;
289
23
  function setExpose(object, propertyName) {
290
24
  const types = Reflect.getMetadata("design:type", object, propertyName);
291
25
  if (types) {
292
- const originMap = (0, lib_1.getOriginMetadata)(lib_1.PARAM_TYPE_KEY, object);
26
+ const originMap = getOriginMetadata(rule_1.PARAM_TYPE_KEY, object);
293
27
  originMap.set(propertyName, types.name);
294
28
  }
295
29
  }
296
30
  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 = (0, lib_1.getOriginMetadata)(lib_1.PARAM_TYPE_KEY, object);
308
- originMap.set(propertyName, types.name);
309
- }
310
- };
31
+ const functionPrototype = Object.getPrototypeOf(Function);
32
+ // get property of an object
33
+ // https://tc39.github.io/ecma262/#sec-ordinarygetprototypeof
34
+ function ordinaryGetPrototypeOf(obj) {
35
+ const proto = Object.getPrototypeOf(obj);
36
+ if (typeof obj !== "function" || obj === functionPrototype) {
37
+ return proto;
38
+ }
39
+ // TypeScript doesn't set __proto__ in ES5, as it's non-standard.
40
+ // Try to determine the superclass constructor. Compatible implementations
41
+ // must either set __proto__ on a subclass constructor to the superclass constructor,
42
+ // or ensure each class has a valid `constructor` property on its prototype that
43
+ // points back to the constructor.
44
+ // If this is not the same as Function.[[Prototype]], then this is definitely inherited.
45
+ // This is the case when in ES6 or when using __proto__ in a compatible browser.
46
+ if (proto !== functionPrototype) {
47
+ return proto;
48
+ }
49
+ // If the super prototype is Object.prototype, null, or undefined, then we cannot determine the heritage.
50
+ const prototype = obj.prototype;
51
+ const prototypeProto = prototype && Object.getPrototypeOf(prototype);
52
+ // tslint:disable-next-line: triple-equals
53
+ if (prototypeProto == undefined || prototypeProto === Object.prototype) {
54
+ return proto;
55
+ }
56
+ // If the constructor was not a function, then we cannot determine the heritage.
57
+ const constructor = prototypeProto.constructor;
58
+ if (typeof constructor !== "function") {
59
+ return proto;
60
+ }
61
+ // If we have some kind of self-reference, then we cannot determine the heritage.
62
+ if (constructor === obj) {
63
+ return proto;
64
+ }
65
+ // we have a pretty good guess at the heritage.
66
+ return constructor;
311
67
  }
312
- exports.Expose = Expose;
313
68
  /**
314
- * Identifies that the field needs to be defined
69
+ * get property metadata data
315
70
  *
316
- * @export
317
- * @returns {PropertyDecorator}
71
+ * @param {(string | symbol)} decoratorNameKey
72
+ * @param {*} target
73
+ * @returns
318
74
  */
319
- function IsDefined() {
320
- return function (object, propertyName) {
321
- setExpose(object, propertyName);
322
- };
75
+ function listPropertyData(decoratorNameKey, target, propertyKey) {
76
+ const originMap = getOriginMetadata(decoratorNameKey, target, propertyKey);
77
+ const data = {};
78
+ for (const [key, value] of originMap) {
79
+ data[key] = value;
80
+ }
81
+ return data;
323
82
  }
324
- exports.IsDefined = IsDefined;
325
83
  /**
326
- * Checks if value is a chinese name.
327
- *
328
- * @export
329
- * @param {string} property
330
- * @param {ValidationOptions} [validationOptions]
331
- * @returns {PropertyDecorator}
84
+ * get metadata value of a metadata key on the prototype chain of an object and property
85
+ * @param metadataKey metadata key
86
+ * @param target the target of metadataKey
332
87
  */
333
- function IsCnName(validationOptions) {
334
- return function (object, propertyName) {
335
- setExpose(object, propertyName);
336
- (0, class_validator_1.registerDecorator)({
337
- name: "IsCnName",
338
- target: object.constructor,
339
- propertyName,
340
- options: validationOptions,
341
- validator: {
342
- validate(value, args) {
343
- return (0, lib_1.cnName)(value);
344
- },
345
- defaultMessage(args) {
346
- return "invalid parameter ($property).";
88
+ function recursiveGetMetadata(metadataKey, target, propertyKey) {
89
+ // get metadata value of a metadata key on the prototype
90
+ // let metadata = Reflect.getOwnMetadata(metadataKey, target, propertyKey);
91
+ const metadata = listPropertyData(metadataKey, target, propertyKey) || {};
92
+ // get metadata value of a metadata key on the prototype chain
93
+ let parent = ordinaryGetPrototypeOf(target);
94
+ while (parent !== null) {
95
+ // metadata = Reflect.getOwnMetadata(metadataKey, parent, propertyKey);
96
+ const pMetadata = listPropertyData(metadataKey, parent, propertyKey);
97
+ if (pMetadata) {
98
+ for (const n in pMetadata) {
99
+ if (!metadata.hasOwnProperty(n)) {
100
+ metadata[n] = pMetadata[n];
347
101
  }
348
102
  }
349
- });
350
- };
103
+ }
104
+ parent = ordinaryGetPrototypeOf(parent);
105
+ }
106
+ return metadata;
351
107
  }
352
- exports.IsCnName = IsCnName;
108
+ exports.recursiveGetMetadata = recursiveGetMetadata;
353
109
  /**
354
- * Checks if value is a idCard number(chinese).
110
+ * Dynamically add methods for target class types
355
111
  *
356
- * @export
357
- * @param {string} property
358
- * @param {ValidationOptions} [validationOptions]
359
- * @returns {PropertyDecorator}
112
+ * @param {Function} clazz
113
+ * @param {string} protoName
114
+ * @param {Function} func
360
115
  */
361
- function IsIdNumber(validationOptions) {
362
- return function (object, propertyName) {
363
- setExpose(object, propertyName);
364
- (0, class_validator_1.registerDecorator)({
365
- name: "IsIdNumber",
366
- target: object.constructor,
367
- propertyName,
368
- options: validationOptions,
369
- validator: {
370
- validate(value, args) {
371
- return (0, lib_1.idNumber)(value);
372
- },
373
- defaultMessage(args) {
374
- return "invalid parameter ($property).";
375
- }
116
+ function defineNewProperty(clazz, protoName, func) {
117
+ const oldMethod = Reflect.get(clazz.prototype, protoName);
118
+ if (oldMethod) {
119
+ Reflect.defineProperty(clazz.prototype, protoName, {
120
+ writable: true,
121
+ value: function fn(...props) {
122
+ // process paramter
123
+ props = func(props);
124
+ // tslint:disable-next-line: no-invalid-this
125
+ return Reflect.apply(oldMethod, this, props);
376
126
  }
377
127
  });
378
- };
128
+ }
379
129
  }
380
- exports.IsIdNumber = IsIdNumber;
130
+ exports.defineNewProperty = defineNewProperty;
381
131
  /**
382
- * Checks if value is a zipCode(chinese).
383
132
  *
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
- (0, class_validator_1.registerDecorator)({
393
- name: "IsZipCode",
394
- target: object.constructor,
395
- propertyName,
396
- options: validationOptions,
397
- validator: {
398
- validate(value, args) {
399
- return (0, 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
133
  *
412
- * @export
413
- * @param {string} property
414
- * @param {ValidationOptions} [validationOptions]
415
- * @returns {PropertyDecorator}
134
+ * @param {(string | symbol)} metadataKey
135
+ * @param {*} target
136
+ * @param {(string | symbol)} [propertyKey]
137
+ * @returns
416
138
  */
417
- function IsMobile(validationOptions) {
418
- return function (object, propertyName) {
419
- setExpose(object, propertyName);
420
- (0, class_validator_1.registerDecorator)({
421
- name: "IsMobile",
422
- target: object.constructor,
423
- propertyName,
424
- options: validationOptions,
425
- validator: {
426
- validate(value, args) {
427
- return (0, lib_1.mobile)(value);
428
- },
429
- defaultMessage(args) {
430
- return "invalid parameter ($property).";
431
- }
432
- }
433
- });
434
- };
139
+ function getOriginMetadata(metadataKey, target, propertyKey) {
140
+ // filter Object.create(null)
141
+ if (typeof target === "object" && target.constructor) {
142
+ target = target.constructor;
143
+ }
144
+ if (propertyKey) {
145
+ // for property or method
146
+ if (!Reflect.hasMetadata(metadataKey, target, propertyKey)) {
147
+ Reflect.defineMetadata(metadataKey, new Map(), target, propertyKey);
148
+ }
149
+ return Reflect.getMetadata(metadataKey, target, propertyKey);
150
+ }
151
+ else {
152
+ // for class
153
+ if (!Reflect.hasMetadata(metadataKey, target)) {
154
+ Reflect.defineMetadata(metadataKey, new Map(), target);
155
+ }
156
+ return Reflect.getMetadata(metadataKey, target);
157
+ }
435
158
  }
436
- exports.IsMobile = IsMobile;
159
+ exports.getOriginMetadata = getOriginMetadata;
437
160
  /**
438
- * Checks if value is a plate number(chinese).
439
161
  *
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
- (0, class_validator_1.registerDecorator)({
449
- name: "IsPlateNumber",
450
- target: object.constructor,
451
- propertyName,
452
- options: validationOptions,
453
- validator: {
454
- validate(value, args) {
455
- return (0, 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
162
  *
468
163
  * @export
469
- * @param {ValidationOptions} [validationOptions]
470
- * @returns {PropertyDecorator}
164
+ * @param {*} clazz
165
+ * @param {*} data
166
+ * @param {boolean} [convert=false]
167
+ * @returns
471
168
  */
472
- function IsNotEmpty(validationOptions) {
473
- return function (object, propertyName) {
474
- setExpose(object, propertyName);
475
- (0, 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
- }
169
+ function plainToClass(clazz, data, convert = false) {
170
+ try {
171
+ if (helper.isClass(clazz)) {
172
+ let cls;
173
+ if (!helper.isObject(data)) {
174
+ data = {};
487
175
  }
488
- });
489
- };
490
- }
491
- exports.IsNotEmpty = IsNotEmpty;
492
- /**
493
- * Checks if value matches ("===") the comparison.
494
- *
495
- * @export
496
- * @param {*} comparison
497
- * @param {ValidationOptions} [validationOptions]
498
- * @returns {PropertyDecorator}
499
- */
500
- function Equals(comparison, validationOptions) {
501
- return function (object, propertyName) {
502
- setExpose(object, propertyName);
503
- (0, class_validator_1.registerDecorator)({
504
- name: "vEquals",
505
- target: object.constructor,
506
- propertyName,
507
- options: validationOptions,
508
- validator: {
509
- validate(value, args) {
510
- return (0, class_validator_1.equals)(value, comparison);
511
- },
512
- defaultMessage(args) {
513
- return `invalid parameter, ($property) must be equals ${comparison}.`;
514
- }
176
+ if (data instanceof clazz) {
177
+ cls = data;
515
178
  }
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
- (0, class_validator_1.registerDecorator)({
532
- name: "vNotEquals",
533
- target: object.constructor,
534
- propertyName,
535
- options: validationOptions,
536
- validator: {
537
- validate(value, args) {
538
- return (0, class_validator_1.notEquals)(value, comparison);
539
- },
540
- defaultMessage(args) {
541
- return `invalid parameter, ($property) must be not equals ${comparison}.`;
542
- }
179
+ else {
180
+ cls = Reflect.construct(clazz, []);
543
181
  }
544
- });
545
- };
546
- }
547
- exports.NotEquals = NotEquals;
548
- /**
549
- * Checks if the string contains the seed.
550
- *
551
- * @export
552
- * @param {string} seed
553
- * @param {ValidationOptions} [validationOptions]
554
- * @returns {PropertyDecorator}
555
- */
556
- function Contains(seed, validationOptions) {
557
- return function (object, propertyName) {
558
- setExpose(object, propertyName);
559
- (0, class_validator_1.registerDecorator)({
560
- name: "vContains",
561
- target: object.constructor,
562
- propertyName,
563
- options: validationOptions,
564
- validator: {
565
- validate(value, args) {
566
- return (0, 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}.`;
571
- }
182
+ if (convert) {
183
+ return convertDtoParamsType(clazz, cls, data);
572
184
  }
573
- });
574
- };
185
+ return Object.assign(cls, data);
186
+ }
187
+ return data;
188
+ }
189
+ catch (err) {
190
+ koatty_logger_1.DefaultLogger.Error(err);
191
+ return data;
192
+ }
575
193
  }
576
- exports.Contains = Contains;
194
+ exports.plainToClass = plainToClass;
577
195
  /**
578
- * Checks if given value is in a array of allowed values.
196
+ * convertDtoParamsType
579
197
  *
580
- * @export
581
- * @param {any[]} possibleValues
582
- * @param {ValidationOptions} [validationOptions]
583
- * @returns {PropertyDecorator}
198
+ * @param {*} clazz
199
+ * @param {*} cls
200
+ * @param {*} data
201
+ * @returns {*}
584
202
  */
585
- function IsIn(possibleValues, validationOptions) {
586
- return function (object, propertyName) {
587
- setExpose(object, propertyName);
588
- (0, class_validator_1.registerDecorator)({
589
- name: "vIsIn",
590
- target: object.constructor,
591
- propertyName,
592
- options: validationOptions,
593
- validator: {
594
- validate(value, args) {
595
- return (0, class_validator_1.isIn)(value, possibleValues);
596
- },
597
- defaultMessage(args) {
598
- return `invalid parameter ($property).`;
599
- }
600
- }
601
- });
602
- };
203
+ function convertDtoParamsType(clazz, cls, data) {
204
+ const originMap = getOriginMetadata(rule_1.PARAM_TYPE_KEY, clazz);
205
+ for (const [key, type] of originMap) {
206
+ if (key && Object.prototype.hasOwnProperty.call(data, key)) {
207
+ cls[key] = convertParamsType(data[key], type);
208
+ }
209
+ }
210
+ return cls;
603
211
  }
604
- exports.IsIn = IsIn;
212
+ exports.convertDtoParamsType = convertDtoParamsType;
605
213
  /**
606
- * Checks if given value not in a array of allowed values.
214
+ * 绑定参数类型转换
607
215
  *
608
- * @export
609
- * @param {any[]} possibleValues
610
- * @param {ValidationOptions} [validationOptions]
611
- * @returns {PropertyDecorator}
216
+ * @param {*} param
217
+ * @param {string} type
218
+ * @returns {*}
612
219
  */
613
- function IsNotIn(possibleValues, validationOptions) {
614
- return function (object, propertyName) {
615
- setExpose(object, propertyName);
616
- (0, class_validator_1.registerDecorator)({
617
- name: "vIsNotIn",
618
- target: object.constructor,
619
- propertyName,
620
- options: validationOptions,
621
- validator: {
622
- validate(value, args) {
623
- return (0, class_validator_1.isNotIn)(value, possibleValues);
624
- },
625
- defaultMessage(args) {
626
- return `invalid parameter ($property).`;
220
+ function convertParamsType(param, type) {
221
+ try {
222
+ switch (type) {
223
+ case "Number":
224
+ case "number":
225
+ if (helper.isNaN(param)) {
226
+ return NaN;
627
227
  }
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
- (0, class_validator_1.registerDecorator)({
644
- name: "vIsDate",
645
- target: object.constructor,
646
- propertyName,
647
- options: validationOptions,
648
- validator: {
649
- validate(value, args) {
650
- return (0, class_validator_1.isDate)(value);
651
- },
652
- defaultMessage(args) {
653
- return `invalid parameter ($property).`;
228
+ if (helper.isNumber(param)) {
229
+ return param;
654
230
  }
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
- (0, 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).`;
231
+ if (helper.isNumberString(param)) {
232
+ return helper.toNumber(param);
682
233
  }
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
- (0, 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).`;
234
+ return NaN;
235
+ case "Boolean":
236
+ case "boolean":
237
+ return !!param;
238
+ case "Array":
239
+ case "array":
240
+ case "Tuple":
241
+ case "tuple":
242
+ if (helper.isArray(param)) {
243
+ return param;
710
244
  }
711
- }
712
- });
713
- };
245
+ return helper.toArray(param);
246
+ case "String":
247
+ case "string":
248
+ if (helper.isString(param)) {
249
+ return param;
250
+ }
251
+ return helper.toString(param);
252
+ case "Null":
253
+ case "null":
254
+ return null;
255
+ case "Undefined":
256
+ case "undefined":
257
+ return undefined;
258
+ case "Bigint":
259
+ case "bigint":
260
+ if (typeof param === 'bigint') {
261
+ return param;
262
+ }
263
+ return BigInt(param);
264
+ // case "object":
265
+ // case "enum":
266
+ default: //any
267
+ return param;
268
+ }
269
+ }
270
+ catch (err) {
271
+ return param;
272
+ }
714
273
  }
715
- exports.Max = Max;
274
+ exports.convertParamsType = convertParamsType;
716
275
  /**
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.
276
+ * Check the base types.
719
277
  *
720
- * @export
721
- * @param {number} min
722
- * @param {number} [max]
723
- * @param {ValidationOptions} [validationOptions]
724
- * @returns {PropertyDecorator}
278
+ * @param {*} value
279
+ * @param {string} type
280
+ * @returns {*}
725
281
  */
726
- function Length(min, max, validationOptions) {
727
- return function (object, propertyName) {
728
- setExpose(object, propertyName);
729
- (0, class_validator_1.registerDecorator)({
730
- name: "vLength",
731
- target: object.constructor,
732
- propertyName,
733
- options: validationOptions,
734
- validator: {
735
- validate(value, args) {
736
- return (0, class_validator_1.length)(value, min, max);
737
- },
738
- defaultMessage(args) {
739
- return `invalid parameter ($property).`;
740
- }
282
+ function checkParamsType(value, type) {
283
+ switch (type) {
284
+ case "Number":
285
+ case "number":
286
+ if (!helper.isNumber(value) || helper.isNaN(value)) {
287
+ return false;
741
288
  }
742
- });
743
- };
289
+ return true;
290
+ case "Boolean":
291
+ case "boolean":
292
+ if (!helper.isBoolean(value)) {
293
+ return false;
294
+ }
295
+ return true;
296
+ case "Array":
297
+ case "array":
298
+ case "Tuple":
299
+ case "tuple":
300
+ if (!helper.isArray(value)) {
301
+ return false;
302
+ }
303
+ return true;
304
+ case "String":
305
+ case "string":
306
+ if (!helper.isString(value)) {
307
+ return false;
308
+ }
309
+ return true;
310
+ case "Object":
311
+ case "object":
312
+ case "Enum":
313
+ case "enum":
314
+ if (helper.isTrueEmpty(value)) {
315
+ return false;
316
+ }
317
+ return true;
318
+ case "Null":
319
+ case "null":
320
+ if (!helper.isNull(value)) {
321
+ return false;
322
+ }
323
+ return true;
324
+ case "Undefined":
325
+ case "undefined":
326
+ if (!helper.isUndefined(value)) {
327
+ return false;
328
+ }
329
+ return true;
330
+ case "Bigint":
331
+ case "bigint":
332
+ if (typeof value !== 'bigint') {
333
+ return false;
334
+ }
335
+ return true;
336
+ default: //any
337
+ return true;
338
+ }
744
339
  }
745
- exports.Length = Length;
340
+ exports.checkParamsType = checkParamsType;
746
341
  /**
747
- * Checks if the string is an email. If given value is not a string, then it returns false.
342
+ * Checks if value is a chinese name.
748
343
  *
749
- * @export
750
- * @param {IsEmailOptions} [options]
751
- * @param {ValidationOptions} [validationOptions]
752
- * @returns {PropertyDecorator}
344
+ * @param {string} value
345
+ * @returns {boolean}
753
346
  */
754
- function IsEmail(options, validationOptions) {
755
- return function (object, propertyName) {
756
- setExpose(object, propertyName);
757
- (0, class_validator_1.registerDecorator)({
758
- name: "vIsEmail",
759
- target: object.constructor,
760
- propertyName,
761
- options: validationOptions,
762
- validator: {
763
- validate(value, args) {
764
- return (0, class_validator_1.isEmail)(value);
765
- },
766
- defaultMessage(args) {
767
- return `invalid parameter ($property).`;
768
- }
769
- }
770
- });
771
- };
347
+ function cnName(value) {
348
+ const reg = /^([a-zA-Z0-9\u4e00-\u9fa5\·]{1,10})$/;
349
+ return reg.test(value);
772
350
  }
773
- exports.IsEmail = IsEmail;
351
+ exports.cnName = cnName;
774
352
  /**
775
- * Checks if the string is an IP (version 4 or 6). If given value is not a string, then it returns false.
353
+ * Checks if value is a idCard number.
776
354
  *
777
- * @export
778
- * @param {number} [version]
779
- * @param {ValidationOptions} [validationOptions]
780
- * @returns {PropertyDecorator}
355
+ * @param {string} value
356
+ * @returns
781
357
  */
782
- function IsIP(version, validationOptions) {
783
- return function (object, propertyName) {
784
- setExpose(object, propertyName);
785
- (0, class_validator_1.registerDecorator)({
786
- name: "vIsIP",
787
- target: object.constructor,
788
- propertyName,
789
- options: validationOptions,
790
- validator: {
791
- validate(value, args) {
792
- return (0, class_validator_1.isIP)(value, version);
793
- },
794
- defaultMessage(args) {
795
- return `invalid parameter ($property).`;
796
- }
797
- }
798
- });
799
- };
358
+ function idNumber(value) {
359
+ if (/^\d{15}$/.test(value)) {
360
+ return true;
361
+ }
362
+ if ((/^\d{17}[0-9X]$/).test(value)) {
363
+ const vs = '1,0,x,9,8,7,6,5,4,3,2'.split(',');
364
+ const ps = '7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2'.split(',');
365
+ const ss = value.toLowerCase().split('');
366
+ let r = 0;
367
+ for (let i = 0; i < 17; i++) {
368
+ r += ps[i] * ss[i];
369
+ }
370
+ const isOk = (vs[r % 11] === ss[17]);
371
+ return isOk;
372
+ }
373
+ return false;
800
374
  }
801
- exports.IsIP = IsIP;
375
+ exports.idNumber = idNumber;
802
376
  /**
803
- * Checks if the string is a valid phone number.
377
+ * Checks if value is a mobile phone number.
804
378
  *
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}
379
+ * @param {string} value
380
+ * @returns {boolean}
812
381
  */
813
- function IsPhoneNumber(region, validationOptions) {
814
- return function (object, propertyName) {
815
- setExpose(object, propertyName);
816
- (0, class_validator_1.registerDecorator)({
817
- name: "vIsPhoneNumber",
818
- target: object.constructor,
819
- propertyName,
820
- options: validationOptions,
821
- validator: {
822
- validate(value, args) {
823
- return (0, class_validator_1.isPhoneNumber)(value, region);
824
- },
825
- defaultMessage(args) {
826
- return `invalid parameter ($property).`;
827
- }
828
- }
829
- });
830
- };
382
+ function mobile(value) {
383
+ const reg = /^(13|14|15|16|17|18|19)\d{9}$/;
384
+ return reg.test(value);
831
385
  }
832
- exports.IsPhoneNumber = IsPhoneNumber;
386
+ exports.mobile = mobile;
833
387
  /**
834
- * Checks if the string is an url.
388
+ * Checks if value is a zipCode.
835
389
  *
836
- * @export
837
- * @param {IsURLOptions} [options]
838
- * @param {ValidationOptions} [validationOptions]
839
- * @returns {PropertyDecorator}
390
+ * @param {string} value
391
+ * @returns {boolean}
840
392
  */
841
- function IsUrl(options, validationOptions) {
842
- return function (object, propertyName) {
843
- setExpose(object, propertyName);
844
- (0, class_validator_1.registerDecorator)({
845
- name: "vIsUrl",
846
- target: object.constructor,
847
- propertyName,
848
- options: validationOptions,
849
- validator: {
850
- validate(value, args) {
851
- return (0, class_validator_1.isURL)(value, options);
852
- },
853
- defaultMessage(args) {
854
- return `invalid parameter ($property).`;
855
- }
856
- }
857
- });
858
- };
393
+ function zipCode(value) {
394
+ const reg = /^\d{6}$/;
395
+ return reg.test(value);
859
396
  }
860
- exports.IsUrl = IsUrl;
397
+ exports.zipCode = zipCode;
861
398
  /**
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']
399
+ * Checks if value is a plateNumber.
864
400
  *
865
- * @export
866
- * @param {HashAlgorithm} algorithm
867
- * @param {ValidationOptions} [validationOptions]
868
- * @returns {PropertyDecorator}
401
+ * @param {string} value
402
+ * @returns {boolean}
869
403
  */
870
- function IsHash(algorithm, validationOptions) {
871
- return function (object, propertyName) {
872
- setExpose(object, propertyName);
873
- (0, class_validator_1.registerDecorator)({
874
- name: "vIsHash",
875
- target: object.constructor,
876
- propertyName,
877
- options: validationOptions,
878
- validator: {
879
- validate(value, args) {
880
- return (0, 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
- };
404
+ function plateNumber(value) {
405
+ // 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])$');
406
+ // let xReg = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}(([0-9]{5}[DF]$)|([DF][A-HJ-NP-Z0-9][0-9]{4}$))/;
407
+ const xReg = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领]{1}[A-Z]{1}(([0-9]{5}[DF]$)|([DF][A-HJ-NP-Z0-9][0-9]{4}$))/;
408
+ // let cReg = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳]{1}$/;
409
+ const cReg = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领]{1}[A-Z]{1}[A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳]{1}$/;
410
+ if (value.length === 7) {
411
+ return cReg.test(value);
412
+ }
413
+ else {
414
+ //新能源车牌
415
+ return xReg.test(value);
416
+ }
888
417
  }
889
- exports.IsHash = IsHash;
418
+ exports.plateNumber = plateNumber;
890
419
  //# sourceMappingURL=util.js.map