cast.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. 'use strict';
  2. // Load modules
  3. const Hoek = require('hoek');
  4. const Ref = require('./ref');
  5. // Type modules are delay-loaded to prevent circular dependencies
  6. // Declare internals
  7. const internals = {
  8. any: null,
  9. date: require('./date'),
  10. string: require('./string'),
  11. number: require('./number'),
  12. boolean: require('./boolean'),
  13. alt: null,
  14. object: null
  15. };
  16. exports.schema = function (config) {
  17. internals.any = internals.any || new (require('./any'))();
  18. internals.alt = internals.alt || require('./alternatives');
  19. internals.object = internals.object || require('./object');
  20. if (config !== undefined && config !== null && typeof config === 'object') {
  21. if (config.isJoi) {
  22. return config;
  23. }
  24. if (Array.isArray(config)) {
  25. return internals.alt.try(config);
  26. }
  27. if (config instanceof RegExp) {
  28. return internals.string.regex(config);
  29. }
  30. if (config instanceof Date) {
  31. return internals.date.valid(config);
  32. }
  33. return internals.object.keys(config);
  34. }
  35. if (typeof config === 'string') {
  36. return internals.string.valid(config);
  37. }
  38. if (typeof config === 'number') {
  39. return internals.number.valid(config);
  40. }
  41. if (typeof config === 'boolean') {
  42. return internals.boolean.valid(config);
  43. }
  44. if (Ref.isRef(config)) {
  45. return internals.any.valid(config);
  46. }
  47. Hoek.assert(config === null, 'Invalid schema content:', config);
  48. return internals.any.valid(null);
  49. };
  50. exports.ref = function (id) {
  51. return Ref.isRef(id) ? id : Ref.create(id);
  52. };