Skip to content

Commit

Permalink
eslint; code style
Browse files Browse the repository at this point in the history
  • Loading branch information
epoberezkin committed Feb 2, 2016
1 parent 7a391fd commit 89a5ce7
Show file tree
Hide file tree
Showing 10 changed files with 132 additions and 78 deletions.
28 changes: 28 additions & 0 deletions .eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
{
"rules": {
"indent": [ 2, 2, {"SwitchCase": 1} ],
"quotes": [ 2, "single", "avoid-escape" ],
"linebreak-style": [ 2, "unix" ],
"semi": [ 2, "always" ],
"valid-jsdoc": [ 2, { "requireReturn": false } ],
"no-console": 0,
"block-scoped-var": 2,
"complexity": [2, 13],
"curly": [2, "multi-or-nest", "consistent"],
"dot-location": [2, "property"],
"dot-notation": 2,
"no-else-return": 2,
"no-eq-null": 2,
"no-fallthrough": 2,
"no-return-assign": 2,
"strict": [2, "global"],
"no-shadow": 0,
"no-use-before-define": [2, "nofunc"],
"callback-return": 2
},
"env": {
"node": true,
"browser": true
},
"extends": "eslint:recommended"
}
19 changes: 11 additions & 8 deletions lib/ajv.js
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ function Ajv(opts) {

/**
* Create validating function for passed schema.
* @param {String|Object} schema
* @param {Object} schema schema object
* @return {Function} validating function
*/
function compile(schema) {
Expand All @@ -103,8 +103,10 @@ function Ajv(opts) {

/**
* Adds schema to the instance.
* @param {Object|Array} schema schema or array of schemas. If array is passed, `key` will be ignored.
* @param {Object|Array} schema schema or array of schemas. If array is passed, `key` and other parameters will be ignored.
* @param {String} key Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`.
* @param {Boolean} _skipValidation true to skip schema validation. Used internally, option validateSchema should be used instead.
* @param {Boolean} _meta true if schema is a meta-schema. Used internally, addMetaSchema should be used instead.
*/
function addSchema(schema, key, _skipValidation, _meta) {
if (Array.isArray(schema)){
Expand All @@ -122,19 +124,20 @@ function Ajv(opts) {
/**
* Add schema that will be used to validate other schemas
* options in META_IGNORE_OPTIONS are alway set to false
* @param {Object} schema
* @param {Object} schema schema object
* @param {String} key optional schema key
* @param {Boolean} skipValidation true to skip schema validation, can be used to override validateSchema option for meta-schema
*/
function addMetaSchema(schema, key, _skipValidation) {
addSchema(schema, key, _skipValidation, true);
function addMetaSchema(schema, key, skipValidation) {
addSchema(schema, key, skipValidation, true);
}


/**
* Validate schema
* @param {Object} schema schema to validate
* @param {Boolean} throwOrLogError pass true to throw (or log) an error if invalid
* @return {Boolean}
* @return {Boolean} true if schema is valid
*/
function validateSchema(schema, throwOrLogError) {
var $schema = schema.$schema || (self._opts.v5 ? v5.META_SCHEMA_ID : META_SCHEMA_ID);
Expand Down Expand Up @@ -218,7 +221,7 @@ function Ajv(opts) {
id: id,
schema: schema,
localRefs: localRefs,
jsonStr: jsonStr,
jsonStr: jsonStr
});

if (id[0] != '#' && shouldAddSchema) self._refs[id] = schemaObj;
Expand Down Expand Up @@ -283,7 +286,7 @@ function Ajv(opts) {
* Convert array of error message objects to string
* @param {Array<Object>} errors optional array of validation errors, if not passed errors from the instance are used.
* @param {Object} opts optional options with properties `separator` and `dataVar`.
* @return {String}
* @return {String} human readable string with all errors descriptions
*/
function errorsText(errors, opts) {
errors = errors || self.errors;
Expand Down
35 changes: 17 additions & 18 deletions lib/async.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ var util = require('./compile/util');
var ASYNC = {
'*': checkGenerators,
'co*': checkGenerators,
'es7': checkAsyncFunction,
'es7': checkAsyncFunction
};

var TRANSPILE = {
Expand Down Expand Up @@ -135,9 +135,9 @@ function nodentTranspile(code) {


/**
* Create validating function for passed schema with asynchronous loading of missing schemas.
* Creates validating function for passed schema with asynchronous loading of missing schemas.
* `loadSchema` option should be a function that accepts schema uri and node-style callback.
* @param {String|Object} schema
* @param {Object} schema schema object
* @param {Function} callback node-style callback, it is always called with 2 parameters: error (or null) and validating function.
*/
function compileAsync(schema, callback) {
Expand All @@ -150,9 +150,9 @@ function compileAsync(schema, callback) {
setTimeout(function() { callback(e); });
return;
}
if (schemaObj.validate)
if (schemaObj.validate) {
setTimeout(function() { callback(null, schemaObj.validate); });
else {
} else {
if (typeof this._opts.loadSchema != 'function')
throw new Error('options.loadSchema should be a function');
_compileAsync(schema, callback, true);
Expand Down Expand Up @@ -184,33 +184,32 @@ function compileAsync(schema, callback) {
self._opts.loadSchema(ref, function (err, sch) {
var _callbacks = self._loadingSchemas[ref];
delete self._loadingSchemas[ref];
if (typeof _callbacks == 'function')
if (typeof _callbacks == 'function') {
_callbacks(err, sch);
else
} else {
for (var i=0; i<_callbacks.length; i++)
_callbacks[i](err, sch);
}
});
}

function schemaLoaded(err, sch) {
if (err) callback(err);
else {
if (!(self._refs[ref] || self._schemas[ref])) {
try {
self.addSchema(sch, ref);
} catch(e) {
callback(e);
return;
}
if (err) return callback(err);
if (!(self._refs[ref] || self._schemas[ref])) {
try {
self.addSchema(sch, ref);
} catch(e) {
callback(e);
return;
}
_compileAsync(schema, callback);
}
_compileAsync(schema, callback);
}
}

function deferCallback(err, validate) {
if (firstCall) setTimeout(function() { callback(err, validate); });
else callback(err, validate);
else return callback(err, validate);
}
}
}
8 changes: 4 additions & 4 deletions lib/cache.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,20 @@


var Cache = module.exports = function Cache() {
this._cache = {};
this._cache = {};
};


Cache.prototype.put = function Cache_put(key, value) {
this._cache[key] = value;
this._cache[key] = value;
};


Cache.prototype.get = function Cache_get(key) {
return this._cache[key];
return this._cache[key];
};


Cache.prototype.del = function Cache_del(key) {
delete this._cache[key];
delete this._cache[key];
};
33 changes: 23 additions & 10 deletions lib/compile/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,24 @@

var resolve = require('./resolve')
, util = require('./util')
, equal = require('./equal')
, stableStringify = require('json-stable-stringify')
, async = require('../async')
, co = require('co');
, async = require('../async');

var beautify = (function() { try { return require('' + 'js-beautify').js_beautify; } catch(e) {} })();
var beautify = (function() { try { return require('' + 'js-beautify').js_beautify; } catch(e) {/*empty*/} })();

var validateGenerator = require('../dotjs/validate');

module.exports = compile;


/**
* Compiles schema to validation function
* @param {Object} schema schema object
* @param {Object} root object with information about the root schema for this schema
* @param {Object} localRefs the hash of local references inside the schema (created by resolve.id), used for inline resolution
* @param {String} baseId base ID for IDs in the schema
* @return {Function} validation function
*/
function compile(schema, root, localRefs, baseId) {
/* jshint validthis: true, evil: true */
var self = this
Expand All @@ -24,8 +30,7 @@ function compile(schema, root, localRefs, baseId) {
, patternsHash = {}
, defaults = []
, defaultsHash = {}
, customRules = []
, customRulesHash = {};
, customRules = [];

root = root || { schema: schema, refVal: refVal, refs: refs };

Expand Down Expand Up @@ -186,15 +191,16 @@ function compile(schema, root, localRefs, baseId) {
, macro = rule.definition.macro;

var validate;
if (compile)
if (compile) {
validate = compile.call(self, schema, parentSchema);
else if (macro) {
} else if (macro) {
validate = macro.call(self, schema, parentSchema);
if (opts.validateSchema !== false) self.validateSchema(validate, true);
} else if (inline)
} else if (inline) {
validate = inline.call(self, it, rule.keyword, schema, parentSchema);
else
} else {
validate = rule.definition.validate;
}

var index = customRules.length;
customRules[index] = validate;
Expand Down Expand Up @@ -236,12 +242,19 @@ function vars(arr, statement) {
}


/*eslint-disable no-unused-vars */

/**
* Functions below are used inside compiled validations function
*/

var co = require('co');

var ucs2length = util.ucs2length;

var equal = require('./equal');

// this error is thrown by async schemas to return validation errors via exception
var ValidationError = require('./validation_error');

/*eslint-enable no-unused-vars */
37 changes: 24 additions & 13 deletions lib/compile/resolve.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,15 @@ resolve.url = resolveUrl;
resolve.ids = resolveIds;
resolve.inlineRef = inlineRef;

/**
* [resolve and compile the references ($ref)]
* @this {Ajv} ajv instence
* @param {Function} comple reference to schema compilation funciton (localCompile)
* @param {Object} root object with information about the root schema for the current schema
* @param {String} ref reference to resolve
* @return {Object|Function} schema object (if the schema can be inlined) or validation function
*/

function resolve(compile, root, ref) {
/* jshint validthis: true */
var refVal = this._refs[ref];
Expand All @@ -22,10 +31,11 @@ function resolve(compile, root, ref) {
}

refVal = refVal || this._schemas[ref];
if (refVal instanceof SchemaObject)
if (refVal instanceof SchemaObject) {
return inlineRef(refVal.schema, this._opts.inlineRefs)
? refVal.schema
: refVal.validate || this._compile(refVal);
}

var res = _resolve.call(this, root, ref);
var schema, v, baseId;
Expand All @@ -35,12 +45,13 @@ function resolve(compile, root, ref) {
baseId = res.baseId;
}

if (schema instanceof SchemaObject)
if (schema instanceof SchemaObject) {
v = schema.validate || compile.call(this, schema.schema, root, undefined, baseId);
else if (schema)
} else if (schema) {
v = inlineRef(schema, this._opts.inlineRefs)
? schema
: compile.call(this, schema, root, undefined, baseId);
}

return v;
}
Expand Down Expand Up @@ -143,10 +154,8 @@ function checkNoRef(schema) {
} else {
for (var key in schema) {
if (key == '$ref') return false;
else {
item = schema[key];
if (typeof item == 'object' && !checkNoRef(item)) return false;
}
item = schema[key];
if (typeof item == 'object' && !checkNoRef(item)) return false;
}
}
return true;
Expand All @@ -164,8 +173,9 @@ function countKeys(schema) {
} else {
for (var key in schema) {
if (key == '$ref') return Infinity;
if (SIMPLE_INLINED[key]) count++;
else {
if (SIMPLE_INLINED[key]) {
count++;
} else {
item = schema[key];
if (typeof item == 'object') count += countKeys(item) + 1;
if (count == Infinity) return Infinity;
Expand All @@ -190,7 +200,7 @@ function _getFullPath(p) {

var TRAILING_SLASH_HASH = /#\/?$/;
function normalizeId(id) {
return id ? id.replace(TRAILING_SLASH_HASH, '') : '';
return id ? id.replace(TRAILING_SLASH_HASH, '') : '';
}


Expand All @@ -209,10 +219,10 @@ function resolveIds(schema) {

function _resolveIds(schema, fullPath, baseId) {
/* jshint validthis: true */
if (Array.isArray(schema))
if (Array.isArray(schema)) {
for (var i=0; i<schema.length; i++)
_resolveIds.call(this, schema[i], fullPath+'/'+i, baseId);
else if (schema && typeof schema == 'object') {
} else if (schema && typeof schema == 'object') {
if (typeof schema.id == 'string') {
var id = baseId = baseId
? url.resolve(baseId, schema.id)
Expand All @@ -229,8 +239,9 @@ function resolveIds(schema) {
if (localRefs[id] && !equal(schema, localRefs[id]))
throw new Error('id "' + id + '" resolves to more than one schema');
localRefs[id] = schema;
} else
} else {
this._refs[id] = fullPath;
}
}
}
for (var key in schema)
Expand Down
2 changes: 1 addition & 1 deletion lib/compile/schema_obj.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,5 @@ var util = require('./util');
module.exports = SchemaObject;

function SchemaObject(obj) {
util.copy(obj, this);
util.copy(obj, this);
}

0 comments on commit 89a5ce7

Please sign in to comment.