isvalid 3.1.3 → 3.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/formalize.js CHANGED
@@ -134,10 +134,6 @@ const formalizeAny = (schema, options = {}) => {
134
134
  });
135
135
  }
136
136
 
137
- const pluginValidators = plugins.validatorsForType(type);
138
-
139
- merge(validators, pluginValidators);
140
-
141
137
  // If post validator is provided allow for options.
142
138
  if (formalizedSchema.pre !== undefined || formalizedSchema.post !== undefined) {
143
139
  merge(validators, { 'options': 'any' });
@@ -148,12 +144,34 @@ const formalizeAny = (schema, options = {}) => {
148
144
  for (let key in formalizedSchema) {
149
145
 
150
146
  let validator = validators[key];
147
+ let test = formalizedSchema[key];
151
148
 
152
- if (validator === undefined) {
153
- throw new SchemaError(schema, `Validator \`${key}\` is unknown in this context.`);
154
- }
149
+ if (typeof validator === 'undefined') {
155
150
 
156
- let test = formalizedSchema[key];
151
+ let plugin;
152
+
153
+ [plugin, validator] = options.plugins
154
+ .filter((plugin) => plugin.supportsType(type))
155
+ .map((plugin) => [plugin, plugin.validatorsForType(type)])
156
+ .reduce((plugins, [plugin, validators]) => {
157
+ if (Object.keys(validators).includes(key)) {
158
+ validators = validators[key];
159
+ if (!Array.isArray(validators)) validators = [validators];
160
+ return [plugin, validators.map((validator) => utils.typeName(validator))];
161
+ }
162
+ return plugins;
163
+ }, []);
164
+
165
+ if (typeof plugin === 'undefined') throw new SchemaError(schema, `Validator \`${key}\` is unknown in this context.`);
166
+
167
+ formalizedSchema.plugins = formalizedSchema.plugins || {};
168
+ formalizedSchema.plugins[key] = {
169
+ phase: plugin.phase || 'post',
170
+ validator: plugin.validate,
171
+ formalize: plugin.formalize
172
+ };
173
+
174
+ }
157
175
 
158
176
  // Test for - and transform - errors in validator.
159
177
  if (Array.isArray(test) &&
@@ -173,13 +191,21 @@ const formalizeAny = (schema, options = {}) => {
173
191
  }
174
192
 
175
193
  // Ensure validator is of correct type.
176
- if (validator !== 'any' && validator.indexOf(utils.instanceTypeName(test)) == -1) {
194
+ if (typeof validator !== 'undefined' && validator !== 'any' && validator.indexOf(utils.instanceTypeName(test)) == -1) {
177
195
  throw new SchemaError(
178
196
  schema,
179
197
  `Validator '${key}' must be of type(s) ${validators[key].join(', ')}.`
180
198
  );
181
199
  }
182
200
 
201
+ if (typeof (formalizedSchema.plugins || {})[key] !== 'undefined') {
202
+ try {
203
+ formalizedSchema[key] = formalizedSchema.plugins[key].formalize(formalizedSchema[key], key, type) || formalizedSchema[key];
204
+ } catch (error) {
205
+ throw new SchemaError(schema, error.message);
206
+ }
207
+ }
208
+
183
209
  if (typeof (options.transform || {}).post === 'function') {
184
210
  const transformed = options.transform.post(key, formalizedSchema[key], { schema: formalizedSchema }) || formalizedSchema[key];
185
211
  formalizedSchema[key] = typeof transformed !== 'undefined' ? transformed : formalizedSchema[key];
@@ -275,22 +301,15 @@ const formalizeAny = (schema, options = {}) => {
275
301
  }
276
302
  }
277
303
 
278
- for (const validator of Object.keys(pluginValidators)) {
279
- try {
280
- const result = plugins.formalizeValidator(type, validator, formalizedSchema[validator]) || formalizedSchema[validator];
281
- if (typeof result !== 'undefined') formalizedSchema[validator] = result;
282
- } catch (error) {
283
- throw new SchemaError(
284
- schema,
285
- error.message);
286
- }
287
- }
288
-
289
304
  return finalize(formalizedSchema, schema);
290
305
 
291
306
  };
292
307
 
293
- exports = module.exports = formalizeAny;
308
+ exports = module.exports = (schema, options = {}) => {
309
+ return formalizeAny(schema, Object.assign({}, options, {
310
+ plugins: plugins._plugins.concat(options.plugins || [])
311
+ }));
312
+ };
294
313
 
295
314
  exports.strip = (schema) => {
296
315
  return Object.keys(schema)
package/lib/plugins.js CHANGED
@@ -1,54 +1,12 @@
1
1
  'use strict';
2
2
 
3
3
  const
4
- merge = require('merge'),
5
4
  utils = require('./utils');
6
5
 
7
6
  exports = module.exports = {
8
7
  _plugins: []
9
8
  };
10
9
 
11
- exports.use = function(plugin) {
12
- this._plugins.push(merge(plugin(utils), {
13
- _validatorsForType: function(type) {
14
- return Object.fromEntries(
15
- Object.entries(
16
- this.validatorsForType(type))
17
- .map(([key, value]) => {
18
- if (typeof value !== 'string') value = utils.typeName(value);
19
- return [key, !Array.isArray(value) ? [value] : value];
20
- })
21
- );
22
- }
23
- }));
24
- };
25
-
26
- exports.validatorsForType = function(type, phase) {
27
- return Object.fromEntries(Object.entries(merge(...this._plugins
28
- .filter((plugin) => (!phase || (plugin.phase || 'post') === phase) && plugin.supportsType(type))
29
- .map((plugin) => plugin._validatorsForType(type)))));
30
-
31
- };
32
-
33
- exports.formalizeValidator = function(type, identifier, config) {
34
- return this._plugins
35
- .filter((plugin) => plugin.supportsType(type))
36
- .filter((plugin) => Object.keys(plugin._validatorsForType(type)).includes(identifier))
37
- .reduce((config, plugin) => {
38
- if (typeof plugin.formalizeValidator !== 'function') return config;
39
- return plugin.formalizeValidator(config, identifier, type);
40
- }, config);
41
- };
42
-
43
- exports.validate = async function(type, identifier, config, data) {
44
-
45
- const plugins = this._plugins
46
- .filter((plugin) => plugin.supportsType(type));
47
-
48
- for (const plugin of plugins) {
49
- data = await plugin.validate(data, config, identifier, type);
50
- }
51
-
52
- return data;
53
-
10
+ exports.use = (plugin) => {
11
+ exports._plugins.push(plugin(utils));
54
12
  };
package/lib/validate.js CHANGED
@@ -5,8 +5,7 @@ const ValidationError = require('./errors/validation.js'),
5
5
  unique = require('./unique.js'),
6
6
  formalize = require('./formalize.js'),
7
7
  utils = require('./utils.js'),
8
- equals = require('./equals.js'),
9
- plugins = require('./plugins.js');
8
+ equals = require('./equals.js');
10
9
 
11
10
  const checkBoolValue = (name, schema, defaults) => {
12
11
  if (schema[name] === undefined) return defaults[name] === true;
@@ -318,19 +317,20 @@ const validateCustom = async (phase, data, schema, options, keyPath, validatedDa
318
317
 
319
318
  const validatePlugins = async (phase, data, schema, options, keyPath) => {
320
319
 
321
- const pluginValidators = Object.keys(plugins.validatorsForType(schema.type, phase))
322
- .filter((validator) => typeof schema[validator] !== 'undefined');
320
+ const plugins = Object.keys(schema.plugins || {})
321
+ .filter((key) => schema.plugins[key].phase === phase)
322
+ .map((key) => [key, schema.plugins[key].validator]);
323
323
 
324
- for (const pluginValidator of pluginValidators) {
324
+ for (let idx = 0 ; idx < plugins.length ; idx++) {
325
+ const [key, validator] = plugins[idx];
325
326
  try {
326
- data = await plugins.validate(schema.type, pluginValidator, schema[pluginValidator], data);
327
+ data = await validator(data, schema[key], key, schema.type);
327
328
  } catch (error) {
328
329
  throw new ValidationError(
329
330
  keyPath,
330
331
  schema._nonFormalizedSchema,
331
- pluginValidator,
332
- (schema.errors || {})[pluginValidator] || customErrorMessage((options.errorMessages || {})[pluginValidator] || error.message)
333
- );
332
+ key,
333
+ (schema.errors || {})[key] || customErrorMessage((options.errorMessages || {})[key] || error.message));
334
334
  }
335
335
  }
336
336
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "isvalid",
3
- "version": "3.1.3",
3
+ "version": "3.2.0",
4
4
  "description": "Async JSON validation library for node.js.",
5
5
  "main": "./index.js",
6
6
  "keywords": [
package/test/formalize.js CHANGED
@@ -6,7 +6,7 @@ const expect = require('chai').expect,
6
6
 
7
7
  const f = (...args) => {
8
8
  return () => {
9
- formalize(...args);
9
+ return formalize(...args);
10
10
  };
11
11
  };
12
12
 
@@ -183,7 +183,9 @@ describe('schema', function() {
183
183
  expect(f({ type: String, nonExistingValidator: 'myValue' })).to.throw(SchemaError);
184
184
  });
185
185
  it ('should throw error if plugin validator fails formalizing.', () => {
186
- expect(f({ type: String, casing: 'not-supported' })).to.throw(SchemaError);
186
+ expect(f({ type: String, ensureCase: 'not-supported' }))
187
+ .to.throw(SchemaError)
188
+ .with.property('message', 'Only case types: `camel`, `domain`, `http`, `kebab`, `lower`, `pascal`, `snake`, `title`, `upper` are supported.');
187
189
  });
188
190
  });
189
191
  });
package/test/index.js CHANGED
@@ -11,7 +11,7 @@ isvalid.plugins.use(function (utils) {
11
11
  return {
12
12
  supportsType: (type) => utils.isSameType(type, String),
13
13
  validatorsForType: () => { return { ensureCase: String }; },
14
- formalizeValidator: (config) => {
14
+ formalize: (config) => {
15
15
  if (config && !caseit.supported.includes(config)) throw new Error(`Only case types: ${caseit.supported.map((casing) => `\`${casing}\``).join(', ')} are supported.`);
16
16
  },
17
17
  validate: (data, config) => {