validno 0.1.9 → 0.1.11

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/Schema.js CHANGED
@@ -5,7 +5,8 @@ export const defaultSchemaKeys = [
5
5
  "eachType",
6
6
  "rules",
7
7
  "title",
8
- "customMessage"
8
+ "customMessage",
9
+ "joinErrors"
9
10
  ];
10
11
  export class Schema {
11
12
  constructor(inputSchema) {
package/dist/dev.js ADDED
@@ -0,0 +1,41 @@
1
+ import { Schema } from "./Schema.js";
2
+ const schema = new Schema({
3
+ ops1: {
4
+ type: Number,
5
+ required: true,
6
+ title: 'titl',
7
+ customMessage: (input) => {
8
+ return 'Wrong type 1 msg ' + input.keyword;
9
+ }
10
+ },
11
+ ops2: {
12
+ type: String,
13
+ required: true,
14
+ title: 'titl',
15
+ customMessage: (input) => {
16
+ return 'Missing msg ' + input.keyword;
17
+ }
18
+ },
19
+ miss: {
20
+ type: String,
21
+ required: true,
22
+ title: 'titl',
23
+ customMessage: (input) => {
24
+ return 'Missing msg ' + input.keyword;
25
+ }
26
+ }
27
+ });
28
+ const obj = {
29
+ ops1: 'String',
30
+ ops2: 123
31
+ };
32
+ const obj2 = {
33
+ ops1: 222,
34
+ ops2: 'str',
35
+ miss: 'here'
36
+ };
37
+ const res = schema.validate(obj);
38
+ const res2 = schema.validate(obj2);
39
+ console.log('finalResult');
40
+ console.log(res2);
41
+ console.log(res2.joinErrors());
package/dist/validate.js CHANGED
@@ -1,9 +1,13 @@
1
- import checkRules from "./checkRules.js";
2
1
  import checkType from "./checkType.js";
3
2
  import _errors from "./utils/errors.js";
3
+ import checkRules from "./checkRules.js";
4
4
  import _validations from "./utils/validations.js";
5
- import { defaultSchemaKeys } from "./Schema.js";
6
5
  import { ErrorKeywords } from "./constants/details.js";
6
+ import { defaultSchemaKeys } from "./Schema.js";
7
+ function joinErrors(separator = ';') {
8
+ var _a;
9
+ return ((_a = this.errors) === null || _a === void 0 ? void 0 : _a.join(`${separator} `)) || '';
10
+ }
7
11
  export const getResultDefaults = () => {
8
12
  return {
9
13
  ok: null,
@@ -78,6 +82,9 @@ export function handleReqKey(key, data, reqs, deepKey = key) {
78
82
  results.missed.push(deepKey);
79
83
  results.failed.push(deepKey);
80
84
  results.errors.push(errMsg);
85
+ if (deepKey in results.errorsByKeys === false)
86
+ results.errorsByKeys[deepKey] = [];
87
+ results.errorsByKeys[deepKey].push(errMsg);
81
88
  results.byKeys[deepKey] = false;
82
89
  return results;
83
90
  }
@@ -129,7 +136,23 @@ function validate(schema, data, onlyKeys) {
129
136
  results.ok = false;
130
137
  else
131
138
  results.ok = true;
132
- return results;
139
+ return new ValidnoResult(results);
133
140
  }
134
141
  ;
142
+ class ValidnoResult {
143
+ constructor(results) {
144
+ this.ok = results.ok;
145
+ this.missed = results.missed;
146
+ this.failed = results.failed;
147
+ this.passed = results.passed;
148
+ this.errors = results.errors;
149
+ this.byKeys = results.byKeys;
150
+ this.errorsByKeys = results.errorsByKeys;
151
+ this.byKeys = results.byKeys;
152
+ }
153
+ joinErrors(separator = '; ') {
154
+ var _a;
155
+ return ((_a = this.errors) === null || _a === void 0 ? void 0 : _a.join(`${separator} `)) || '';
156
+ }
157
+ }
135
158
  export default validate;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "validno",
3
- "version": "0.1.9",
3
+ "version": "0.1.11",
4
4
  "description": "",
5
5
  "main": "dist/index.js",
6
6
  "scripts": {
package/src/Schema.ts DELETED
@@ -1,46 +0,0 @@
1
- import validate from "./validate.js"
2
-
3
- export type TSchemaItem = {
4
- required: boolean,
5
- type: any,
6
- eachType?: any,
7
- rules?: {},
8
- title?: string,
9
- customMessage?: Function
10
- }
11
-
12
- export type TSchemaInput = {
13
- [key: string]: TSchemaItem | TSchemaInput
14
- }
15
-
16
- export const enum ESchemaFields {
17
- Required = 'required',
18
- Type = 'type',
19
- EachType = 'eachType',
20
- Rules = 'rules',
21
- Title = 'title',
22
- CustomMessage = 'customMessage'
23
- }
24
-
25
- export const defaultSchemaKeys = [
26
- ESchemaFields.Required,
27
- ESchemaFields.Type,
28
- ESchemaFields.EachType,
29
- ESchemaFields.Rules,
30
- ESchemaFields.Title,
31
- ESchemaFields.CustomMessage
32
- ]
33
-
34
- export type TSchema = TSchemaInput
35
-
36
- export class Schema {
37
- schema: TSchema
38
-
39
- constructor(inputSchema: TSchema) {
40
- this.schema = inputSchema
41
- }
42
-
43
- validate(data: any, keys?: string | string[]) {
44
- return validate.call(this, this, data, keys)
45
- }
46
- }
package/src/checkRules.ts DELETED
@@ -1,196 +0,0 @@
1
- import { ErrorKeywords } from "./constants/details.js";
2
- import { TSchema, TSchemaItem } from "./Schema.js";
3
- import _validations from "./utils/validations.js"
4
-
5
- export type TRule = {[key: string]: any}
6
-
7
- type TLengths = string | Array<any>
8
-
9
- export const rulesParams = {
10
- lengthMin: {
11
- allowedTypes: [String]
12
- }
13
- }
14
-
15
- const ensureRuleHasCorrectType = (value: any, allowedTypes: any[]) => {
16
- const isInAllowedList = allowedTypes.some(TYPE => {
17
- const getType = (el: any) => Object.prototype.toString.call(el)
18
- return getType(new TYPE()) == getType(value)
19
- })
20
-
21
- return isInAllowedList
22
- }
23
-
24
- const rulesFunctions: any = {
25
- custom: (key: string, val: any, func: Function, extra: {schema: TSchema, input: {[key: string]: any}}) => {
26
- return func(val, extra)
27
- },
28
- isEmail: (key: string, val: any) => {
29
- return {
30
- result: _validations.isEmail(val),
31
- details: `Значение должно соответствовать формату name@email.ru`
32
- }
33
- },
34
- is: (key: string, val: any, equalTo: any) => {
35
- return {
36
- result: _validations.is(val, equalTo),
37
- details: `Значение должно быть "${equalTo}"`
38
- }
39
- },
40
- isNot: (key: string, val: any, notEqualTo: any) => {
41
- return {
42
- result: _validations.isNot(val, notEqualTo),
43
- details: `Значение "${notEqualTo}" недопустимо`
44
- }
45
- },
46
- min: (key: string, val: number, min: number) => {
47
- return {
48
- result: _validations.isNumberGte(val, min),
49
- details: "Значение не может быть меньше " + min
50
- }
51
- },
52
- max: (key: string, val: number, max: number) => {
53
- return {
54
- result: _validations.isNumberLte(val, max),
55
- details: "Значение не может быть больше " + max
56
- }
57
- },
58
- minMax: (key: string, val: number, minMax: [min: number, max: number]) => {
59
- const [min, max] = minMax
60
- return {
61
- result: _validations.isNumberGte(val, min) && _validations.isNumberLte(val, max),
62
- details: `Значение должно быть в пределах ${min}-${max}`
63
- }
64
- },
65
- length: (key: string, val: TLengths, length: number) => {
66
- return {
67
- result: _validations.lengthIs(val, length),
68
- details: "Количество символов должно быть равным " + length
69
- }
70
- },
71
- lengthNot: (key: string, val: TLengths, lengthNot: number) => {
72
- return {
73
- result: _validations.lengthNot(val, lengthNot),
74
- details: "Количество символов не должно быть равным " + lengthNot
75
- }
76
- },
77
- lengthMinMax: (key: string, val: TLengths, minMax: [min: number, max: number]) => {
78
- const [min, max] = minMax
79
-
80
- return {
81
- result: _validations.lengthMin(val, min) && _validations.lengthMax(val, max),
82
- details: `Длина должна быть от ${min} до ${max} символов`
83
- }
84
- },
85
- lengthMin: (key: string, val: TLengths, min: number) => {
86
- ensureRuleHasCorrectType(val, rulesParams['lengthMin'].allowedTypes)
87
-
88
- return {
89
- result: _validations.lengthMin(val, min),
90
- details: `Длина не может быть меньше ${min} символов`
91
- }
92
- },
93
- lengthMax: (key: string, val: TLengths, max: number) => {
94
- return {
95
- result: _validations.lengthMax(val, max),
96
- details: `Длина не может быть больше ${max} символов`
97
- }
98
- },
99
- regex: (key: string, val: any, regex: RegExp) => {
100
- return {
101
- result: _validations.regexTested(val, regex),
102
- details: "Значение не соответствует допустимому формату"
103
- }
104
- },
105
- enum: (key: string, value: any, allowedList: any[]) => {
106
- const output = {
107
- result: true,
108
- details: ''
109
- }
110
-
111
- if (!Array.isArray(value)) {
112
- const isCorrect = allowedList.includes(value)
113
- output.result = isCorrect,
114
- output.details = isCorrect ? '' : `Значение "${value}" недопустимо`
115
- } else {
116
- const incorrectValues: any[] = []
117
- value.forEach((v: any) => !allowedList.includes(v) ? incorrectValues.push(v): {})
118
- const isCorrect = incorrectValues.length === 0
119
-
120
- output.result = isCorrect,
121
- output.details = isCorrect ? '' : `Значения недопустимы: "${incorrectValues.join(', ')}"`
122
- }
123
-
124
- return output
125
- }
126
- };
127
-
128
- type TRulesResult = {
129
- ok: boolean,
130
- details: string[]
131
- }
132
-
133
- function checkRules (this: any, key: string, value: any, requirements: TSchemaItem, inputObj: any) {
134
- const result: TRulesResult = {
135
- ok: true,
136
- details: []
137
- };
138
-
139
- // Значение отсутствует, но НЕ является обязательным
140
- if (requirements.required !== true && value === undefined) return result
141
-
142
- // Для этого ключа нет правил
143
- if (!requirements || !requirements.rules || !Object.keys(requirements.rules).length) {
144
- return result
145
- }
146
-
147
- const rules: TRule = requirements.rules
148
- const title = requirements.title || key
149
-
150
- const allResults = []
151
- const allRulesKeys = Object.keys(rules)
152
-
153
- let i = 0;
154
- while (i < allRulesKeys.length) {
155
- const ruleName = allRulesKeys[i]
156
-
157
- // Если правило, указанное для ключа, отсутствует в списке доступных
158
- if (ruleName in rulesFunctions === false) {
159
- i++
160
- continue
161
- }
162
-
163
- const func = rulesFunctions[ruleName]
164
- const args = rules[ruleName]
165
-
166
- const result = func(key, value, args, {schema: this.schema, input: inputObj})
167
-
168
- if (requirements.customMessage && typeof requirements.customMessage === 'function') {
169
- result.details = requirements.customMessage({
170
- keyword: ruleName,
171
- value: value,
172
- key: key,
173
- title: title,
174
- reqs: requirements,
175
- schema: this.schema,
176
- rules: rules,
177
- })
178
- }
179
-
180
- allResults.push(result)
181
-
182
- i++;
183
- }
184
-
185
- // If key has failed rules checks
186
- const failedResults = allResults.filter(el => el.result === false)
187
-
188
- if (failedResults.length) {
189
- result.ok = false
190
- result.details = failedResults.map(el => el.details)
191
- }
192
-
193
- return result;
194
- };
195
-
196
- export default checkRules
package/src/checkType.ts DELETED
@@ -1,213 +0,0 @@
1
- import { ErrorKeywords } from "./constants/details.js";
2
- import { TSchemaInput, TSchemaItem } from "./Schema.js";
3
- import _validations from "./utils/validations.js";
4
-
5
- const getErrorDetails = (key: string, expectedType: any, receivedValue: any) => {
6
- let receivedType = ''
7
-
8
- if (typeof receivedValue === 'string') receivedType = 'String'
9
- else if (typeof receivedValue === 'number') receivedType = 'Number'
10
- else if (typeof receivedValue === 'boolean') receivedType = 'Noolean'
11
- else if (receivedValue === null) receivedType = 'null'
12
- else if (Array.isArray(receivedValue)) receivedType = 'Array'
13
- else if (_validations.isDate(receivedValue)) receivedType = 'Date'
14
- else if (_validations.isObject(receivedValue)) receivedType = 'Object'
15
- else if (receivedValue === undefined) receivedType = 'undefined'
16
-
17
- return `Проверьте тип "${key}": ожидался ${expectedType?.name || expectedType}, получен ${receivedType || 'unknown'}`;
18
- };
19
-
20
- const checkTypeMultiple = (key: string, value: any, requirements: TSchemaItem | TSchemaInput, keyName = key) => {
21
- const constructorNames = requirements.type.map((el:any) => String(el?.name || el))
22
-
23
- const result = {
24
- key: keyName,
25
- passed: false,
26
- details: getErrorDetails(keyName, constructorNames.join('/'), value)
27
- };
28
-
29
- let i = 0;
30
- while (i < requirements.type.length) {
31
- const requirementsRe = { ...requirements, type: requirements.type[i]}
32
- const check = checkType(key, value, requirementsRe)
33
-
34
- if (check[0].passed === true) {
35
- result.passed = true
36
- result.details = 'OK'
37
- return result
38
- }
39
-
40
- i++
41
- }
42
-
43
- return result
44
- }
45
-
46
- type TCheckTypeResult = {key: string, passed: boolean, details: string}
47
-
48
- const checkType = (key: string, value: any, requirements: TSchemaItem | TSchemaInput, keyName = key): TCheckTypeResult[] => {
49
- const isNotNull = value !== null
50
- const keyTitle = 'title' in requirements ? requirements.title : keyName
51
- const hasCustomMessage = requirements.customMessage && typeof requirements.customMessage === 'function'
52
-
53
- if (value === undefined && requirements.required) {
54
- return [{key: keyName, passed: false, details: `Значение "${keyName}" отсутствует`}]
55
- }
56
-
57
- let result: TCheckTypeResult[] = []
58
-
59
- if (Array.isArray(requirements.type)) {
60
- return [checkTypeMultiple(key, value, requirements)]
61
- }
62
-
63
- if (value === undefined && requirements.required !== true) {
64
- result.push({
65
- key: keyName,
66
- passed: true,
67
- details: 'OK'
68
- })
69
- return result
70
- }
71
-
72
-
73
- const customErrDetails = hasCustomMessage ?
74
- //@ts-ignore
75
- requirements.customMessage({
76
- keyword: ErrorKeywords.Type,
77
- value: value,
78
- key: keyName,
79
- title: keyTitle,
80
- reqs: requirements,
81
- schema: null
82
- }) :
83
- null;
84
-
85
- const baseErrDetails = getErrorDetails(keyName, requirements.type, value)
86
-
87
- const getDetails = (isOK: boolean) => isOK ? 'OK' : customErrDetails || baseErrDetails
88
-
89
- switch (requirements.type) {
90
- case 'any':
91
- result.push({
92
- key: keyName,
93
- passed: true,
94
- details: 'OK'
95
- })
96
- break;
97
- case Number:
98
- const isNumber = isNotNull && value.constructor === Number
99
-
100
- result.push({
101
- key: keyName,
102
- passed: isNumber,
103
- details: getDetails(isNumber)
104
- })
105
-
106
- break;
107
- case String:
108
- const isString = isNotNull && value.constructor === String
109
-
110
- result.push({
111
- key: keyName,
112
- passed: isString,
113
- details: getDetails(isString)
114
- })
115
- break;
116
- case Date:
117
- const isDate = isNotNull && value.constructor === Date
118
- const isValid = isDate && !isNaN(value.getTime())
119
- const errorMsg = isValid ? getDetails(isDate) : 'Дата невалидна'
120
-
121
- result.push({
122
- key: keyName,
123
- passed: isDate && isValid,
124
- details: isDate && isValid ? 'OK' : errorMsg
125
- })
126
- break;
127
- case Boolean:
128
- const isBoolean = isNotNull && value.constructor === Boolean
129
-
130
- result.push({
131
- key: keyName,
132
- passed: isBoolean,
133
- details: isBoolean ? 'OK' : getDetails(isBoolean)
134
- })
135
- break;
136
- case Array:
137
- const isArray = isNotNull && value.constructor === Array
138
-
139
- if (!isArray) {
140
- result.push({
141
- key: keyName,
142
- passed: false,
143
- details: getDetails(isArray)
144
- });
145
-
146
- break;
147
- }
148
-
149
- let isEachChecked = { passed: true, details: ""}
150
-
151
- if ('eachType' in requirements) {
152
- isEachChecked.passed = value.every((el: any) => {
153
- const checkResult = checkType('each of ' + key, el, {type: requirements.eachType, required: true})
154
-
155
- if (!checkResult[0].passed) {
156
- isEachChecked.details = checkResult[0].details
157
- isEachChecked.passed = false
158
- }
159
-
160
- return true
161
- })
162
- }
163
-
164
- const isOk = isArray && isEachChecked.passed
165
-
166
- result.push({
167
- key: keyName,
168
- passed: isOk,
169
- details: isOk ? 'OK' : !isEachChecked.passed ? isEachChecked.details : getDetails(isOk)
170
- })
171
-
172
- break;
173
- case Object:
174
- const isObject = _validations.isObject(value) && value.constructor === Object
175
-
176
- result.push({
177
- key: keyName,
178
- passed: isObject,
179
- details: isObject ? 'OK' : getDetails(isObject)
180
- })
181
-
182
- break;
183
- case RegExp:
184
- const isRegex = _validations.isRegex(value)
185
- result.push({
186
- key: keyName,
187
- passed: isRegex,
188
- details: isRegex ? 'OK' : getDetails(isRegex)
189
- })
190
-
191
- break;
192
- case null:
193
- const isNull = value === null
194
-
195
- result.push({
196
- key: keyName,
197
- passed: isNull,
198
- details: isNull ? 'OK' : getDetails(isNull)
199
- })
200
-
201
- break;
202
- default:
203
- result.push({
204
- key: keyName,
205
- passed: false,
206
- details: `Тип '${keyName}' не определен`
207
- })
208
- }
209
-
210
- return result;
211
- };
212
-
213
- export default checkType
@@ -1,5 +0,0 @@
1
- export enum ErrorKeywords {
2
- Missing = 'missing',
3
- Type = 'type',
4
- Rule = 'rule'
5
- }
package/src/index.ts DELETED
@@ -1,3 +0,0 @@
1
- import { Schema } from "./Schema.js";
2
-
3
- export default Schema