index.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. 'use strict';
  2. // Load modules
  3. const Hoek = require('hoek');
  4. const Any = require('./any');
  5. const Cast = require('./cast');
  6. const Errors = require('./errors');
  7. const Lazy = require('./lazy');
  8. const Ref = require('./ref');
  9. // Declare internals
  10. const internals = {
  11. alternatives: require('./alternatives'),
  12. array: require('./array'),
  13. boolean: require('./boolean'),
  14. binary: require('./binary'),
  15. date: require('./date'),
  16. number: require('./number'),
  17. object: require('./object'),
  18. string: require('./string')
  19. };
  20. internals.root = function () {
  21. const any = new Any();
  22. const root = any.clone();
  23. root.any = function () {
  24. return any;
  25. };
  26. root.alternatives = root.alt = function () {
  27. return arguments.length ? internals.alternatives.try.apply(internals.alternatives, arguments) : internals.alternatives;
  28. };
  29. root.array = function () {
  30. return internals.array;
  31. };
  32. root.boolean = root.bool = function () {
  33. return internals.boolean;
  34. };
  35. root.binary = function () {
  36. return internals.binary;
  37. };
  38. root.date = function () {
  39. return internals.date;
  40. };
  41. root.func = function () {
  42. return internals.object._func();
  43. };
  44. root.number = function () {
  45. return internals.number;
  46. };
  47. root.object = function () {
  48. return arguments.length ? internals.object.keys.apply(internals.object, arguments) : internals.object;
  49. };
  50. root.string = function () {
  51. return internals.string;
  52. };
  53. root.ref = function () {
  54. return Ref.create.apply(null, arguments);
  55. };
  56. root.isRef = function (ref) {
  57. return Ref.isRef(ref);
  58. };
  59. root.validate = function (value /*, [schema], [options], callback */) {
  60. const last = arguments[arguments.length - 1];
  61. const callback = typeof last === 'function' ? last : null;
  62. const count = arguments.length - (callback ? 1 : 0);
  63. if (count === 1) {
  64. return any.validate(value, callback);
  65. }
  66. const options = count === 3 ? arguments[2] : {};
  67. const schema = root.compile(arguments[1]);
  68. return schema._validateWithOptions(value, options, callback);
  69. };
  70. root.describe = function () {
  71. const schema = arguments.length ? root.compile(arguments[0]) : any;
  72. return schema.describe();
  73. };
  74. root.compile = function (schema) {
  75. try {
  76. return Cast.schema(schema);
  77. }
  78. catch (err) {
  79. if (err.hasOwnProperty('path')) {
  80. err.message = err.message + '(' + err.path + ')';
  81. }
  82. throw err;
  83. }
  84. };
  85. root.assert = function (value, schema, message) {
  86. root.attempt(value, schema, message);
  87. };
  88. root.attempt = function (value, schema, message) {
  89. const result = root.validate(value, schema);
  90. const error = result.error;
  91. if (error) {
  92. if (!message) {
  93. error.message = error.annotate();
  94. throw error;
  95. }
  96. if (!(message instanceof Error)) {
  97. error.message = message + ' ' + error.annotate();
  98. throw error;
  99. }
  100. throw message;
  101. }
  102. return result.value;
  103. };
  104. root.reach = function (schema, path) {
  105. Hoek.assert(schema && schema instanceof Any, 'you must provide a joi schema');
  106. Hoek.assert(typeof path === 'string', 'path must be a string');
  107. if (path === '') {
  108. return schema;
  109. }
  110. const parts = path.split('.');
  111. const children = schema._inner.children;
  112. if (!children) {
  113. return;
  114. }
  115. const key = parts[0];
  116. for (let i = 0; i < children.length; ++i) {
  117. const child = children[i];
  118. if (child.key === key) {
  119. return this.reach(child.schema, path.substr(key.length + 1));
  120. }
  121. }
  122. };
  123. root.lazy = function (fn) {
  124. return Lazy.set(fn);
  125. };
  126. root.extend = function () {
  127. const extensions = Hoek.flatten(Array.prototype.slice.call(arguments));
  128. Hoek.assert(extensions.length > 0, 'You need to provide at least one extension');
  129. this.assert(extensions, root.extensionsSchema);
  130. const joi = Object.create(this);
  131. for (let i = 0; i < extensions.length; ++i) {
  132. const extension = extensions[i];
  133. const base = (extension.base || this.any()).clone(); // Cloning because we're going to override language afterwards
  134. const ctor = base.constructor;
  135. const type = class extends ctor { // eslint-disable-line no-loop-func
  136. constructor() {
  137. super();
  138. if (extension.base) {
  139. Object.assign(this, base);
  140. }
  141. this._type = extension.name;
  142. if (extension.language) {
  143. this._settings = this._settings || { language: {} };
  144. this._settings.language = Hoek.applyToDefaults(this._settings.language, {
  145. [extension.name]: extension.language
  146. });
  147. }
  148. }
  149. };
  150. if (extension.coerce) {
  151. type.prototype._coerce = function (value, state, options) {
  152. if (ctor.prototype._coerce) {
  153. const baseRet = ctor.prototype._coerce.call(this, value, state, options);
  154. if (baseRet.errors) {
  155. return baseRet;
  156. }
  157. value = baseRet.value;
  158. }
  159. const ret = extension.coerce.call(this, value, state, options);
  160. if (ret instanceof Errors.Err) {
  161. return { value, errors: ret };
  162. }
  163. return { value: ret };
  164. };
  165. }
  166. if (extension.pre) {
  167. type.prototype._base = function (value, state, options) {
  168. if (ctor.prototype._base) {
  169. const baseRet = ctor.prototype._base.call(this, value, state, options);
  170. if (baseRet.errors) {
  171. return baseRet;
  172. }
  173. value = baseRet.value;
  174. }
  175. const ret = extension.pre.call(this, value, state, options);
  176. if (ret instanceof Errors.Err) {
  177. return { value, errors: ret };
  178. }
  179. return { value: ret };
  180. };
  181. }
  182. if (extension.rules) {
  183. for (let j = 0; j < extension.rules.length; ++j) {
  184. const rule = extension.rules[j];
  185. const ruleArgs = rule.params ?
  186. (rule.params instanceof Any ? rule.params._inner.children.map((k) => k.key) : Object.keys(rule.params)) :
  187. [];
  188. const validateArgs = rule.params ? Cast.schema(rule.params) : null;
  189. type.prototype[rule.name] = function () { // eslint-disable-line no-loop-func
  190. if (arguments.length > ruleArgs.length) {
  191. throw new Error('Unexpected number of arguments');
  192. }
  193. const args = Array.prototype.slice.call(arguments);
  194. let hasRef = false;
  195. const arg = {};
  196. for (let k = 0; k < ruleArgs.length; ++k) {
  197. arg[ruleArgs[k]] = args[k];
  198. if (!hasRef && Ref.isRef(args[k])) {
  199. hasRef = true;
  200. }
  201. }
  202. if (validateArgs) {
  203. joi.assert(arg, validateArgs);
  204. }
  205. let schema;
  206. if (rule.validate) {
  207. const validate = function (value, state, options) {
  208. return rule.validate.call(this, arg, value, state, options);
  209. };
  210. schema = this._test(rule.name, arg, validate, {
  211. description: rule.description,
  212. hasRef
  213. });
  214. }
  215. else {
  216. schema = this.clone();
  217. }
  218. if (rule.setup) {
  219. rule.setup.call(schema, arg);
  220. }
  221. return schema;
  222. };
  223. }
  224. }
  225. if (extension.describe) {
  226. type.prototype.describe = function () {
  227. const description = ctor.prototype.describe.call(this);
  228. return extension.describe.call(this, description);
  229. };
  230. }
  231. const instance = new type();
  232. joi[extension.name] = function () {
  233. return instance;
  234. };
  235. }
  236. return joi;
  237. };
  238. root.extensionsSchema = internals.array.items(internals.object.keys({
  239. base: internals.object.type(Any, 'Joi object'),
  240. name: internals.string.required(),
  241. coerce: internals.object._func().arity(3),
  242. pre: internals.object._func().arity(3),
  243. language: internals.object,
  244. describe: internals.object._func().arity(1),
  245. rules: internals.array.items(internals.object.keys({
  246. name: internals.string.required(),
  247. setup: internals.object._func().arity(1),
  248. validate: internals.object._func().arity(4),
  249. params: [
  250. internals.object.pattern(/.*/, internals.object.type(Any, 'Joi object')),
  251. internals.object.type(internals.object.constructor, 'Joi object')
  252. ],
  253. description: [internals.string, internals.object._func().arity(1)]
  254. }).or('setup', 'validate'))
  255. })).strict();
  256. return root;
  257. };
  258. module.exports = internals.root();