Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

validator.js 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. 'use strict';
  2. var urilib = require('url');
  3. var attribute = require('./attribute');
  4. var helpers = require('./helpers');
  5. var ValidatorResult = helpers.ValidatorResult;
  6. var SchemaError = helpers.SchemaError;
  7. var SchemaContext = helpers.SchemaContext;
  8. /**
  9. * Creates a new Validator object
  10. * @name Validator
  11. * @constructor
  12. */
  13. var Validator = function Validator () {
  14. // Allow a validator instance to override global custom formats or to have their
  15. // own custom formats.
  16. this.customFormats = Object.create(Validator.prototype.customFormats);
  17. this.schemas = {};
  18. this.unresolvedRefs = [];
  19. // Use Object.create to make this extensible without Validator instances stepping on each other's toes.
  20. this.types = Object.create(types);
  21. this.attributes = Object.create(attribute.validators);
  22. };
  23. // Allow formats to be registered globally.
  24. Validator.prototype.customFormats = {};
  25. // Hint at the presence of a property
  26. Validator.prototype.schemas = null;
  27. Validator.prototype.types = null;
  28. Validator.prototype.attributes = null;
  29. Validator.prototype.unresolvedRefs = null;
  30. /**
  31. * Adds a schema with a certain urn to the Validator instance.
  32. * @param schema
  33. * @param urn
  34. * @return {Object}
  35. */
  36. Validator.prototype.addSchema = function addSchema (schema, uri) {
  37. if (!schema) {
  38. return null;
  39. }
  40. var ourUri = uri || schema.id;
  41. this.addSubSchema(ourUri, schema);
  42. if (ourUri) {
  43. this.schemas[ourUri] = schema;
  44. }
  45. return this.schemas[ourUri];
  46. };
  47. Validator.prototype.addSubSchema = function addSubSchema(baseuri, schema) {
  48. if(!schema || typeof schema!='object') return;
  49. // Mark all referenced schemas so we can tell later which schemas are referred to, but never defined
  50. if(schema.$ref){
  51. var resolvedUri = urilib.resolve(baseuri, schema.$ref);
  52. // Only mark unknown schemas as unresolved
  53. if (this.schemas[resolvedUri] === undefined) {
  54. this.schemas[resolvedUri] = null;
  55. this.unresolvedRefs.push(resolvedUri);
  56. }
  57. return;
  58. }
  59. var ourUri = schema.id && urilib.resolve(baseuri, schema.id);
  60. var ourBase = ourUri || baseuri;
  61. if (ourUri) {
  62. if(this.schemas[ourUri]){
  63. if(!helpers.deepCompareStrict(this.schemas[ourUri], schema)){
  64. throw new Error('Schema <'+schema+'> already exists with different definition');
  65. }
  66. return this.schemas[ourUri];
  67. }
  68. this.schemas[ourUri] = schema;
  69. var documentUri = ourUri.replace(/^([^#]*)#$/, '$1');
  70. this.schemas[documentUri] = schema;
  71. }
  72. this.addSubSchemaArray(ourBase, ((schema.items instanceof Array)?schema.items:[schema.items]));
  73. this.addSubSchemaArray(ourBase, ((schema.extends instanceof Array)?schema.extends:[schema.extends]));
  74. this.addSubSchema(ourBase, schema.additionalItems);
  75. this.addSubSchemaObject(ourBase, schema.properties);
  76. this.addSubSchema(ourBase, schema.additionalProperties);
  77. this.addSubSchemaObject(ourBase, schema.definitions);
  78. this.addSubSchemaObject(ourBase, schema.patternProperties);
  79. this.addSubSchemaObject(ourBase, schema.dependencies);
  80. this.addSubSchemaArray(ourBase, schema.disallow);
  81. this.addSubSchemaArray(ourBase, schema.allOf);
  82. this.addSubSchemaArray(ourBase, schema.anyOf);
  83. this.addSubSchemaArray(ourBase, schema.oneOf);
  84. this.addSubSchema(ourBase, schema.not);
  85. return this.schemas[ourUri];
  86. };
  87. Validator.prototype.addSubSchemaArray = function addSubSchemaArray(baseuri, schemas) {
  88. if(!(schemas instanceof Array)) return;
  89. for(var i=0; i<schemas.length; i++){
  90. this.addSubSchema(baseuri, schemas[i]);
  91. }
  92. };
  93. Validator.prototype.addSubSchemaObject = function addSubSchemaArray(baseuri, schemas) {
  94. if(!schemas || typeof schemas!='object') return;
  95. for(var p in schemas){
  96. this.addSubSchema(baseuri, schemas[p]);
  97. }
  98. };
  99. /**
  100. * Sets all the schemas of the Validator instance.
  101. * @param schemas
  102. */
  103. Validator.prototype.setSchemas = function setSchemas (schemas) {
  104. this.schemas = schemas;
  105. };
  106. /**
  107. * Returns the schema of a certain urn
  108. * @param urn
  109. */
  110. Validator.prototype.getSchema = function getSchema (urn) {
  111. return this.schemas[urn];
  112. };
  113. /**
  114. * Validates instance against the provided schema
  115. * @param instance
  116. * @param schema
  117. * @param [options]
  118. * @param [ctx]
  119. * @return {Array}
  120. */
  121. Validator.prototype.validate = function validate (instance, schema, options, ctx) {
  122. if (!options) {
  123. options = {};
  124. }
  125. var propertyName = options.propertyName || 'instance';
  126. // This will work so long as the function at uri.resolve() will resolve a relative URI to a relative URI
  127. var base = urilib.resolve(options.base||'/', schema.id||'');
  128. if(!ctx){
  129. ctx = new SchemaContext(schema, options, propertyName, base, Object.create(this.schemas));
  130. if (!ctx.schemas[base]) {
  131. ctx.schemas[base] = schema;
  132. }
  133. }
  134. if (schema) {
  135. var result = this.validateSchema(instance, schema, options, ctx);
  136. if (!result) {
  137. throw new Error('Result undefined');
  138. }
  139. return result;
  140. }
  141. throw new SchemaError('no schema specified', schema);
  142. };
  143. /**
  144. * @param Object schema
  145. * @return mixed schema uri or false
  146. */
  147. function shouldResolve(schema) {
  148. var ref = (typeof schema === 'string') ? schema : schema.$ref;
  149. if (typeof ref=='string') return ref;
  150. return false;
  151. }
  152. /**
  153. * Validates an instance against the schema (the actual work horse)
  154. * @param instance
  155. * @param schema
  156. * @param options
  157. * @param ctx
  158. * @private
  159. * @return {ValidatorResult}
  160. */
  161. Validator.prototype.validateSchema = function validateSchema (instance, schema, options, ctx) {
  162. var result = new ValidatorResult(instance, schema, options, ctx);
  163. if (!schema) {
  164. throw new Error("schema is undefined");
  165. }
  166. if (schema['extends']) {
  167. if (schema['extends'] instanceof Array) {
  168. var schemaobj = {schema: schema, ctx: ctx};
  169. schema['extends'].forEach(this.schemaTraverser.bind(this, schemaobj));
  170. schema = schemaobj.schema;
  171. schemaobj.schema = null;
  172. schemaobj.ctx = null;
  173. schemaobj = null;
  174. } else {
  175. schema = helpers.deepMerge(schema, this.superResolve(schema['extends'], ctx));
  176. }
  177. }
  178. var switchSchema;
  179. if (switchSchema = shouldResolve(schema)) {
  180. var resolved = this.resolve(schema, switchSchema, ctx);
  181. var subctx = new SchemaContext(resolved.subschema, options, ctx.propertyPath, resolved.switchSchema, ctx.schemas);
  182. return this.validateSchema(instance, resolved.subschema, options, subctx);
  183. }
  184. var skipAttributes = options && options.skipAttributes || [];
  185. // Validate each schema attribute against the instance
  186. for (var key in schema) {
  187. if (!attribute.ignoreProperties[key] && skipAttributes.indexOf(key) < 0) {
  188. var validatorErr = null;
  189. var validator = this.attributes[key];
  190. if (validator) {
  191. validatorErr = validator.call(this, instance, schema, options, ctx);
  192. } else if (options.allowUnknownAttributes === false) {
  193. // This represents an error with the schema itself, not an invalid instance
  194. throw new SchemaError("Unsupported attribute: " + key, schema);
  195. }
  196. if (validatorErr) {
  197. result.importErrors(validatorErr);
  198. }
  199. }
  200. }
  201. if (typeof options.rewrite == 'function') {
  202. var value = options.rewrite.call(this, instance, schema, options, ctx);
  203. result.instance = value;
  204. }
  205. return result;
  206. };
  207. /**
  208. * @private
  209. * @param Object schema
  210. * @param SchemaContext ctx
  211. * @returns Object schema or resolved schema
  212. */
  213. Validator.prototype.schemaTraverser = function schemaTraverser (schemaobj, s) {
  214. schemaobj.schema = helpers.deepMerge(schemaobj.schema, this.superResolve(s, schemaobj.ctx));
  215. }
  216. /**
  217. * @private
  218. * @param Object schema
  219. * @param SchemaContext ctx
  220. * @returns Object schema or resolved schema
  221. */
  222. Validator.prototype.superResolve = function superResolve (schema, ctx) {
  223. var ref;
  224. if(ref = shouldResolve(schema)) {
  225. return this.resolve(schema, ref, ctx).subschema;
  226. }
  227. return schema;
  228. }
  229. /**
  230. * @private
  231. * @param Object schema
  232. * @param Object switchSchema
  233. * @param SchemaContext ctx
  234. * @return Object resolved schemas {subschema:String, switchSchema: String}
  235. * @throws SchemaError
  236. */
  237. Validator.prototype.resolve = function resolve (schema, switchSchema, ctx) {
  238. switchSchema = ctx.resolve(switchSchema);
  239. // First see if the schema exists under the provided URI
  240. if (ctx.schemas[switchSchema]) {
  241. return {subschema: ctx.schemas[switchSchema], switchSchema: switchSchema};
  242. }
  243. // Else try walking the property pointer
  244. var parsed = urilib.parse(switchSchema);
  245. var fragment = parsed && parsed.hash;
  246. var document = fragment && fragment.length && switchSchema.substr(0, switchSchema.length - fragment.length);
  247. if (!document || !ctx.schemas[document]) {
  248. throw new SchemaError("no such schema <" + switchSchema + ">", schema);
  249. }
  250. var subschema = helpers.objectGetPath(ctx.schemas[document], fragment.substr(1));
  251. if(subschema===undefined){
  252. throw new SchemaError("no such schema " + fragment + " located in <" + document + ">", schema);
  253. }
  254. return {subschema: subschema, switchSchema: switchSchema};
  255. };
  256. /**
  257. * Tests whether the instance if of a certain type.
  258. * @private
  259. * @param instance
  260. * @param schema
  261. * @param options
  262. * @param ctx
  263. * @param type
  264. * @return {boolean}
  265. */
  266. Validator.prototype.testType = function validateType (instance, schema, options, ctx, type) {
  267. if (typeof this.types[type] == 'function') {
  268. return this.types[type].call(this, instance);
  269. }
  270. if (type && typeof type == 'object') {
  271. var res = this.validateSchema(instance, type, options, ctx);
  272. return res === undefined || !(res && res.errors.length);
  273. }
  274. // Undefined or properties not on the list are acceptable, same as not being defined
  275. return true;
  276. };
  277. var types = Validator.prototype.types = {};
  278. types.string = function testString (instance) {
  279. return typeof instance == 'string';
  280. };
  281. types.number = function testNumber (instance) {
  282. // isFinite returns false for NaN, Infinity, and -Infinity
  283. return typeof instance == 'number' && isFinite(instance);
  284. };
  285. types.integer = function testInteger (instance) {
  286. return (typeof instance == 'number') && instance % 1 === 0;
  287. };
  288. types.boolean = function testBoolean (instance) {
  289. return typeof instance == 'boolean';
  290. };
  291. types.array = function testArray (instance) {
  292. return Array.isArray(instance);
  293. };
  294. types['null'] = function testNull (instance) {
  295. return instance === null;
  296. };
  297. types.date = function testDate (instance) {
  298. return instance instanceof Date;
  299. };
  300. types.any = function testAny (instance) {
  301. return true;
  302. };
  303. types.object = function testObject (instance) {
  304. // TODO: fix this - see #15
  305. return instance && (typeof instance) === 'object' && !(instance instanceof Array) && !(instance instanceof Date);
  306. };
  307. module.exports = Validator;