This repository was archived by the owner on Mar 22, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathabolish.js
More file actions
5542 lines (5157 loc) · 152 KB
/
abolish.js
File metadata and controls
5542 lines (5157 loc) · 152 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
const {Abolish, Rule, ParseRules} = require('abolish');
window.Abolish = Abolish;
window.AbolishRule = Rule;
window.AbolishParseRules = ParseRules;
},{"abolish":2}],2:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ParseRules = exports.Rule = exports.Abolish = void 0;
const Abolish = require("./src/Abolish");
exports.Abolish = Abolish;
const Functions_1 = require("./src/Functions");
Object.defineProperty(exports, "Rule", { enumerable: true, get: function () { return Functions_1.Rule; } });
Object.defineProperty(exports, "ParseRules", { enumerable: true, get: function () { return Functions_1.ParseRules; } });
},{"./src/Abolish":3,"./src/Functions":5}],3:[function(require,module,exports){
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
const StringToRules_1 = __importDefault(require("./StringToRules"));
const GlobalValidators_1 = __importDefault(require("./GlobalValidators"));
const Functions_1 = require("./Functions");
const AbolishError_1 = __importDefault(require("./AbolishError"));
const ObjectModifier_1 = __importDefault(require("./ObjectModifier"));
const lodash_clonedeep_1 = __importDefault(require("lodash.clonedeep"));
/**
* Abolish Class
* @class
*/
class Abolish {
constructor() {
this.validators = {};
this.config = { useStartCaseInErrors: true };
}
/**
* Add single global validator
* @param validator
*/
static addGlobalValidator(validator) {
if (typeof validator === "object" && !Array.isArray(validator)) {
// If no error defined set default error
if (!validator.error)
validator.error = `:param failed {${validator.name}} validation.`;
// Add validator to instance validators
GlobalValidators_1.default[validator.name] = validator;
}
else {
throw new TypeError("addGlobalValidator argument must be an object.");
}
return this;
}
/**
* Add multiple global validators
* @param validators
*/
static addGlobalValidators(validators) {
if (typeof validators === "object") {
validators = Object.values(validators);
}
if (Array.isArray(validators)) {
for (const value of validators) {
Abolish.addGlobalValidator(value);
}
}
else {
throw new TypeError("addGlobalValidators argument must be an array or an object");
}
return this;
}
/**
* Toggle start case in error.
* @param value
*/
useStartCaseInErrors(value = true) {
this.config.useStartCaseInErrors = value;
return this;
}
/**
* addValidator
* @description
* Add validator or array of validators
* @param validator
*/
addValidator(validator) {
if (typeof validator === "object" && !Array.isArray(validator)) {
// If no error defined set default error
if (!validator.error)
validator.error = `:param failed {${validator.name}} validation.`;
// Add validator to instance validators
this.validators[validator.name] = validator;
}
else {
throw new TypeError("addValidator argument must be an object.");
}
return this;
}
/**
* addValidators
* @description
* Add validator or array of validators
* @param validators
*/
addValidators(validators) {
if (typeof validators === "object") {
validators = Object.values(validators);
}
if (Array.isArray(validators)) {
for (const value of validators) {
this.addValidator(value);
}
}
else {
throw new TypeError("addValidators argument must be an array or an object");
}
return this;
}
/**
* Validate
* @description
* Validates given object with rules defined on Abolish instance
* @param {object} object
* @param {object} rules
*/
static validate(object, rules) {
return new this().validate(object, rules);
}
/**
* Validate Async
*
* Waits for all validation defined
* @param object
* @param rules
* @return {Promise<ValidationResult>}
*/
static validateAsync(object, rules) {
return new this().validateAsync(object, rules);
}
/**
* Validate
* @description
* Validates given object with rules defined on Abolish instance
* @param {object} object
* @param {object} rules
* @param {boolean} isAsync
*/
validate(object, rules, isAsync = false) {
let asyncData = {
validated: {},
jobs: [],
keysToBeValidated: [],
includeKeys: []
};
// clone rules
rules = (0, lodash_clonedeep_1.default)(rules);
/**
* Check for wildcard rules (*, $)
*/
let internalWildcardRules = {};
if (rules.hasOwnProperty("*") || rules.hasOwnProperty("$")) {
internalWildcardRules = rules["*"] || rules["$"];
delete rules["*"];
delete rules["$"];
/**
* Convert rules[*] to object if string
* Using StringToRules function
*/
if (typeof internalWildcardRules === "string")
internalWildcardRules = (0, StringToRules_1.default)(internalWildcardRules);
}
/**
* Validated clones original object to prevent modifying values in original object
*/
let validated = { ...object };
/**
* Get Keys to be validated
*/
let includeKeys = [];
if (rules.hasOwnProperty("$include")) {
includeKeys = rules["$include"];
if (!Array.isArray(includeKeys))
throw new Error(`$include has to be an array!`);
delete rules["$include"];
}
let keysToBeValidated = Object.keys(rules);
// Loop through defined rules
for (const rule of keysToBeValidated) {
let ruleData = rules[rule];
/**
* If ruleData is wildcard change rule data to empty object
*/
if (["*", "$"].includes(ruleData))
ruleData = {};
/**
* Convert ruleData to object if string
* Using StringToRules function
*/
if (typeof ruleData === "string") {
ruleData = (0, StringToRules_1.default)(ruleData);
}
else if (Array.isArray(ruleData)) {
ruleData = (0, Functions_1.Rule)(ruleData);
}
/**
* if ruleData has property of $skip then check
*/
let $skip = false;
if (ruleData.hasOwnProperty("$skip")) {
$skip = ruleData["$skip"];
delete ruleData["$skip"];
if (typeof $skip === "function") {
$skip = $skip(validated[rule]);
}
if (typeof $skip !== "boolean") {
throw new Error(`$skip value or resolved function value must be a BOOLEAN in RuleFor: (${rule})`);
}
}
/**
* Run validation if not $skip
*/
if ($skip) {
keysToBeValidated = keysToBeValidated.filter((v) => v !== rule);
}
else {
/**
* if ruleData has property of $name then set to name
*/
let $name = false;
if (ruleData.hasOwnProperty("$name")) {
$name = ruleData["$name"];
delete ruleData["$name"];
if (typeof $name !== "string") {
throw new Error(`$name must be a string in RuleFor: (${rule})`);
}
}
/**
* check if rules has custom error: $error
*/
let $error;
if (ruleData.hasOwnProperty("$error")) {
$error = ruleData["$error"];
delete ruleData["$error"];
// noinspection SuspiciousTypeOfGuard
if (!$error || typeof $error !== "string") {
throw new Error(`$error value must be a STRING in RuleFor: (${rule})`);
}
}
let $errors;
if (ruleData.hasOwnProperty("$errors")) {
$errors = ruleData["$errors"];
delete ruleData["$errors"];
// noinspection SuspiciousTypeOfGuard
if (!$errors || typeof $errors !== "object") {
throw new Error(`$errors value must be an OBJECT in RuleFor: (${rule})`);
}
}
/**
* Append internal Wildcard data
*/
ruleData = { ...internalWildcardRules, ...ruleData };
/**
* Loop through ruleData to check if validators defined exists
*/
for (const validatorName of Object.keys(ruleData)) {
/**
* Throw Error if validator is not defined in global or local validators
*/
if (!this.validators.hasOwnProperty(validatorName) &&
!GlobalValidators_1.default.hasOwnProperty(validatorName)) {
throw new Error(`Validator: {${validatorName}} does not exists but defined in rules`);
}
/**
* Validator of rule defined in rules.
*/
const validator = (this.validators[validatorName] ||
GlobalValidators_1.default[validatorName]);
if (!isAsync && validator.isAsync) {
throw new Error(`Validator: {${validatorName}} is async, use validateAsync method instead.`);
}
/**
* The value of the validator set in rules
* e.g {must: true}
* where "true" is validationOption
*/
const validatorOption = ruleData[validatorName];
/**
* Value of key being validated in object
*/
const objectValue = (0, Functions_1.abolish_Get)(validated, rule);
/**
* If is async push needed data to asyncData
*/
if (isAsync) {
asyncData.jobs.push({
$name,
rule,
validator,
validatorName,
validatorOption,
$error,
$errors
});
}
else {
/**
* Try running validator
*/
let validationResult = false;
try {
/**
* Run Validation
* Passing required helpers
*/
validationResult = validator.validator(objectValue, validatorOption, {
error: (message, data) => new AbolishError_1.default(message, data),
modifier: new ObjectModifier_1.default(validated, rule, $name)
});
}
catch (e) {
/**
* If error when running defined function
* Send error as validationResult with type as 'internal'
*/
return [
{
key: rule,
type: "internal",
validator: validatorName,
message: e.message,
data: e.stack
},
{}
];
}
if (validationResult === false ||
validationResult instanceof AbolishError_1.default) {
let message;
let data = null;
if (validationResult instanceof AbolishError_1.default) {
message = validationResult.message;
data = validationResult.data;
}
message = $error || message;
if ($errors && $errors[validatorName])
message = $errors[validatorName];
/**
* Check if option is stringable
* This is required because a rule option could an array or an object
* and these cannot be converted to string
*
* Only strings and numbers can be parsed as :option
*/
const optionIsStringable = typeof validatorOption === "string" ||
typeof validatorOption === "number" ||
Array.isArray(validatorOption);
/**
* Replace :param with rule converted to upperCase
* and if option is stringable, replace :option with validatorOption
*/
message = (message || validator.error).replace(":param", $name ? $name : (0, Functions_1.abolish_StartCase)(rule, this));
if (optionIsStringable)
message = message.replace(":option", String(validatorOption));
// Return Error using the ValidationResult format
return [
{
key: rule,
type: "validator",
validator: validatorName,
message,
data
},
{}
];
}
}
}
}
}
if (isAsync) {
asyncData.validated = validated;
asyncData.keysToBeValidated = keysToBeValidated;
asyncData.includeKeys = includeKeys;
return asyncData;
}
// abolish_Pick only keys in rules
validated = (0, Functions_1.abolish_Pick)(validated, keysToBeValidated.concat(includeKeys));
return [false, validated];
}
/**
* Validate Async
*
* Waits for all validation defined
* @param object
* @param rules
* @return {Promise<ValidationResult>}
*/
validateAsync(object, rules) {
/**
* abolish_Get asyncData
*/
const asyncData = this.validate(object, rules, true);
/**
* Destruct values in async data
*/
const { validated, jobs, keysToBeValidated, includeKeys } = asyncData;
/**
* Return a promise
*/
return new Promise(async (resolve) => {
/**
* Loop through jobs and run their validators
*/
for (const job of jobs) {
const { $name, rule, validator, validatorName, validatorOption, $error, $errors } = job;
/**
* Value of key being validated in object
*/
const objectValue = (0, Functions_1.abolish_Get)(validated, rule);
let validationResult = false;
try {
/**
* Run Validation
* Passing required helpers
*/
validationResult = await validator.validator(objectValue, validatorOption, {
error: (message, data) => new AbolishError_1.default(message, data),
modifier: new ObjectModifier_1.default(validated, rule, $name)
});
}
catch (e) {
/**
* If error when running defined function
* Send error as validationResult with type as 'internal'
*/
return resolve([
{
key: rule,
type: "internal",
validator: validatorName,
message: e.message,
data: e.stack
},
{}
]);
}
if (validationResult === false || validationResult instanceof AbolishError_1.default) {
let message;
let data = null;
if (validationResult instanceof AbolishError_1.default) {
message = validationResult.message;
data = validationResult.data;
}
message = $error || message;
if ($errors && $errors[validatorName])
message = $errors[validatorName];
/**
* Replace :param with rule converted to upperCase
* and if option is stringable, replace :option with validatorOption
*/
message = (message || validator.error).replace(":param", $name ? $name : (0, Functions_1.abolish_StartCase)(rule, this));
/**
* Check if option is stringable
* This is required because a rule option could an array or an object
* and these cannot be converted to string
*
* Only strings and numbers can be parsed as :option
*/
const optionIsStringable = typeof validatorOption === "string" || typeof validatorOption === "number";
if (optionIsStringable)
message = message.replace(":option", String(validatorOption));
// Return Error using the ValidationResult format
return resolve([
{
key: rule,
type: "validator",
validator: validatorName,
message: message,
data
},
{}
]);
}
}
return resolve([false, (0, Functions_1.abolish_Pick)(validated, keysToBeValidated.concat(includeKeys))]);
});
}
/**
* Enables the use of $joi validator
* @param joi
*/
static useJoi(joi) {
if (!joi) {
try {
joi = require("joi");
}
catch (e) {
throw new Error(`Joi not found! Install Joi`);
}
}
/**
* Add Validator Joi
*/
return this.addGlobalValidator({
name: "$joi",
validator(value, joiSchema, { error, modifier }) {
/**
* Check if schema is Joi Schema
*/
if (!joi.isSchema(joiSchema)) {
return error(`Invalid JOI schema provided for :param`);
}
/**
* Validate value against joiSchema Passed
*/
let validated;
try {
validated = joi.attempt(value, joiSchema);
}
catch (e) {
return error(e.message);
}
/**
* abolish_Set Value for abolish
*/
modifier.setThis(validated);
return true;
}
});
}
/**
* check a variable does not throw error
* @param variable
* @param rules
*/
check(variable, rules) {
const [e, v] = this.validate({ variable }, { variable: rules });
return [e, v === null || v === void 0 ? void 0 : v.variable];
}
/**
* Static Check
* @param variable
* @param rules
*/
static check(variable, rules) {
return new this().check(variable, rules);
}
/**
* Checks a variable Asynchronously
* @param variable
* @param rules
*/
async checkAsync(variable, rules) {
const [e, v] = await this.validateAsync({ variable }, { variable: rules });
return [e, v === null || v === void 0 ? void 0 : v.variable];
}
/**
* Static Check Async
* @param variable
* @param rules
*/
static checkAsync(variable, rules) {
return new this().checkAsync(variable, rules);
}
/**
* Validates a variable
* @param variable
* @param rules
*/
attempt(variable, rules) {
const [e, v] = this.validate({ variable }, { variable: rules });
if (e)
throw new Error(e.message);
return v.variable;
}
/**
* Static Attempt
* @param variable
* @param rules
* @param abolish
*/
static attempt(variable, rules, abolish) {
return new this().attempt(variable, rules);
}
/**
* Validates a variable Asynchronously, Throws error
* @param variable
* @param rules
*/
async attemptAsync(variable, rules) {
const [e, v] = await this.validateAsync({ variable }, { variable: rules });
if (e)
throw new Error(e.message);
return v.variable;
}
/**
* Validates a variable Asynchronously, Throws error
* @param variable
* @param rules
*/
static async attemptAsync(variable, rules) {
return new this().attemptAsync(variable, rules);
}
}
module.exports = Abolish;
},{"./AbolishError":4,"./Functions":5,"./GlobalValidators":6,"./ObjectModifier":7,"./StringToRules":8,"joi":"joi","lodash.clonedeep":9}],4:[function(require,module,exports){
"use strict";
/**
* AbolishError
* @class
* This class can be used to return custom errors to the validation process
*/
class AbolishError {
constructor(message, data) {
this.message = message;
if (data) {
this.data = data;
}
else {
this.data = {};
}
return this;
}
setData(data) {
this.data = data;
return data;
}
}
module.exports = AbolishError;
},{}],5:[function(require,module,exports){
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.skipIfNotDefined = exports.skipIfUndefined = exports.$inline = exports.ParseRules = exports.abolish_Get = exports.abolish_Set = exports.abolish_Pick = exports.Rule = exports.abolish_StartCase = exports.abolish_UpperFirst = void 0;
const StringToRules_1 = __importDefault(require("./StringToRules"));
const lodash_startcase_1 = __importDefault(require("lodash.startcase"));
/**
* Change to string to upperFirst
* @param str
* @constructor
*/
function abolish_UpperFirst(str) {
return str[0].toUpperCase() + str.substr(1);
}
exports.abolish_UpperFirst = abolish_UpperFirst;
/**
* abolish_StartCase
* @param str
* @param abolishInstance
* @constructor
*/
function abolish_StartCase(str, abolishInstance) {
return abolishInstance
? abolishInstance.config.useStartCaseInErrors
? (0, lodash_startcase_1.default)(str)
: str
: (0, lodash_startcase_1.default)(str);
}
exports.abolish_StartCase = abolish_StartCase;
/**
* Converts an array of rules (string | object)[] to one object rule
* @example
* const rule = Rule(['must', {min: 10, max: 20}, '!exact'])
* // will return
* { must: true, min: 10, max: 20, exact: false }
*
* @param rules
* @constructor
*/
function Rule(rules) {
/**
* Convert to array if not array.
*/
if (!Array.isArray(rules)) {
rules = [rules];
}
/**
* Stores generated rules
*/
let generatedRule = {};
/**
* Loop Through each rule
*
* 1. convert to object if string
* 2. add rule to generatedRule object
*/
for (let rule of rules) {
if (typeof rule === "string")
rule = (0, StringToRules_1.default)(rule);
generatedRule = { ...generatedRule, ...rule };
}
return generatedRule;
}
exports.Rule = Rule;
function abolish_Pick(object, keys) {
return keys.reduce((obj, key) => {
if (object && object.hasOwnProperty(key)) {
obj[key] = object[key];
}
return obj;
}, {});
}
exports.abolish_Pick = abolish_Pick;
function abolish_Set(object, path, value) {
if (Object(object) !== object)
return object; // When object is not an object
// If not yet an array, get the keys from the string-path
if (!Array.isArray(path))
path = path.toString().match(/[^.[\]]+/g) || [];
path.slice(0, -1).reduce((a, c, i // Iterate all of them except the last one
) => Object(a[c]) === a[c] // Does the key exist and is its value an object?
? // Yes: then follow that path
a[c]
: // No: create the key. Is the next key a potential array-index?
(a[c] =
Math.abs(path[i + 1]) >> 0 === +path[i + 1]
? [] // Yes: assign a new array object
: {}), // No: assign a new plain object
object)[path[path.length - 1]] = value; // Finally assign the value to the last key
return object; // Return the top-level object to allow chaining
}
exports.abolish_Set = abolish_Set;
function abolish_Get(obj, path, defaultValue) {
if (path.indexOf(".") >= 0) {
const travel = (regexp) => String.prototype.split
.call(path, regexp)
.filter(Boolean)
.reduce((res, key) => (res !== null && res !== undefined ? res[key] : res), obj);
const result = travel(/[,[\]]+?/) || travel(/[,[\].]+?/);
return result === undefined || result === obj ? defaultValue : result;
}
else {
return obj[path];
}
}
exports.abolish_Get = abolish_Get;
function ParseRules(rules) {
/**
* Stores generated rules
*/
let generatedRule = {};
/**
* Loop Through each rule
*
* 1. convert to object if string
* 2. add rule to generatedRule object
*/
for (let key of Object.keys(rules)) {
let rule = rules[key];
/**
* Exclude non rule related super keys e.g $include
*/
if (key === "$include") {
generatedRule[key] = rule;
}
else {
if (typeof rule === "string") {
rule = (0, StringToRules_1.default)(rule);
}
else if (Array.isArray(rule)) {
rule = Rule(rule);
}
generatedRule[key] = rule;
}
}
return generatedRule;
}
exports.ParseRules = ParseRules;
/**
* $inLine object generator
* @param fn
* @param $error
*/
const $inline = (fn, $error) => {
return $error ? { $inline: fn, $error } : { $inline: fn };
};
exports.$inline = $inline;
/**
* Skip if undefined
* @param rule
*/
function skipIfUndefined(rule) {
if (!Array.isArray(rule))
rule = [rule];
return [{ $skip: (v) => v === undefined }].concat(rule);
}
exports.skipIfUndefined = skipIfUndefined;
/**
* Skip if is undefined || null
* @param rule
*/
function skipIfNotDefined(rule) {
if (!Array.isArray(rule))
rule = [rule];
return [{ $skip: (v) => v === undefined || v === null }].concat(rule);
}
exports.skipIfNotDefined = skipIfNotDefined;
},{"./StringToRules":8,"lodash.startcase":11}],6:[function(require,module,exports){
"use strict";
function trimIfString(value) {
return typeof value === "string" ? value.trim() : value;
}
const GlobalValidators = {
must: {
name: "must",
error: ":param is required.",
validator: (value, option) => {
if (!option) {
return true;
}
if (typeof value === "undefined" || value === null) {
return false;
}
else if (typeof value === "string" || Array.isArray(value)) {
return value.length > 0;
}
return true;
}
},
typeof: {
name: "typeof",
error: ":param is not typeOf :option",
validator: (value, option) => {
/**
* If typeof is false then we don't validate this
*/
if (option === false)
return true;
option = option.toLowerCase();
if (option === "array")
return Array.isArray(value);
return typeof value === option;
}
},
exact: {
name: "exact",
validator: (value, option) => {
return value === option;
},
error: ":param failed exact validator"
},
min: {
name: "min",
error: ":param is too small. (Min. :option)",
validator: (value, option, helpers) => {
const isNotNumber = isNaN(value);
/**
* if is string and string is not a valid number,
* or if value is a valid array
* we pass the validation to `minLength`
*/
if ((typeof value === "string" && isNotNumber) || Array.isArray(value))
return GlobalValidators.minLength.validator(value, option, helpers);
// return false if this is not a number
if (isNotNumber)
return false;
// Parse to Number and compare
return Number(value) >= Number(option);
}
},
max: {
name: "max",
error: ":param is too big. (Max. :option)",
validator: (value, option, helpers) => {
const isNotNumber = isNaN(value);
/**
* if is string and string is not a valid number,
* or if value is a valid array
* we pass the validation to `minLength`
*/
if ((typeof value === "string" && isNotNumber) || Array.isArray(value))
return GlobalValidators.maxLength.validator(value, option, helpers);
// return false if this is not a number
if (isNotNumber)
return false;
// Parse to float and compare
return Number(value) <= Number(option);
}
},
minLength: {
name: "minLength",
error: ":param is too short. (Min. :option characters)",
validator: (value, option) => {
if (typeof value !== "string" && !Array.isArray(value))
return false;
value = trimIfString(value);
return value.length >= Number(option);
}
},
maxLength: {
name: "maxLength",
error: ":param is too long. (Max. :option characters)",
validator: (value, option) => {
if (typeof value !== "string" && !Array.isArray(value))
return false;
value = trimIfString(value);
return value.length <= Number(option);
}
},
selectMin: {
name: "selectMin",
error: "Select at-least :option :param.",
validator: (value, option, helpers) => {
return GlobalValidators.minLength.validator(value, option, helpers);
}
},
selectMax: {
name: "selectMax",
error: "Select at-most :option :param.",
validator: (value, option, helpers) => {
return GlobalValidators.maxLength.validator(value, option, helpers);
}
},
$inline: {
name: "$inline",
error: ":param failed inline validation.",
validator: (v, o, helpers) => {
return o(v, helpers);
}
}
};
/**
* abolish_Set an alias for `must` as `required
*/
GlobalValidators.required = Object.assign({}, GlobalValidators.must);
GlobalValidators.required.name = "required";
module.exports = GlobalValidators;
},{}],7:[function(require,module,exports){
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
const Functions_1 = require("./Functions");
const lodash_has_1 = __importDefault(require("lodash.has"));
const lodash_unset_1 = __importDefault(require("lodash.unset"));
/**
* ObjectOnValidation
* Handles object being validated.
*/
class ObjectModifier {
constructor(data, param, name) {
this.data = data;
this.path = param;
this.name = name;
return this;
}
/**
* abolish_Get path of object or return
* @method
* @param path
* @param $default
* @return {*}
*/
get(path, $default = undefined) {
return (0, Functions_1.abolish_Get)(this.data, path, $default);
}
/**
* abolish_Get path of current key being validated
* @method
*/
getThis() {
return this.get(this.path);
}
/**
* Has path in object
* @method
* @param path
* @return {boolean}
*/
has(path) {
return (0, lodash_has_1.default)(this.data, path);
}
/**
* abolish_Set value to path of object
* @method
* @param path
* @param value
* @return {object}
*/
set(path, value) {
return (0, Functions_1.abolish_Set)(this.data, path, value);
}
/**
* abolish_Set value to this param path
* @methods
* @param value
* @return {*}
*/
setThis(value) {
return this.set(this.path, value);
}
/**