schema.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. const HANDLER_KEYS = [
  4. 'default',
  5. 'expected',
  6. 'validate',
  7. 'deprecated',
  8. 'forward',
  9. 'redirect',
  10. 'overlap',
  11. 'preprocess',
  12. 'postprocess',
  13. ];
  14. function createSchema(SchemaConstructor, parameters) {
  15. const schema = new SchemaConstructor(parameters);
  16. const subSchema = Object.create(schema);
  17. for (const handlerKey of HANDLER_KEYS) {
  18. if (handlerKey in parameters) {
  19. subSchema[handlerKey] = normalizeHandler(parameters[handlerKey], schema, Schema.prototype[handlerKey].length);
  20. }
  21. }
  22. return subSchema;
  23. }
  24. exports.createSchema = createSchema;
  25. class Schema {
  26. constructor(parameters) {
  27. this.name = parameters.name;
  28. }
  29. static create(parameters) {
  30. // @ts-ignore: https://github.com/Microsoft/TypeScript/issues/5863
  31. return createSchema(this, parameters);
  32. }
  33. default(_utils) {
  34. return undefined;
  35. }
  36. // istanbul ignore next: this is actually an abstract method but we need a placeholder to get `function.length`
  37. expected(_utils) {
  38. return 'nothing';
  39. }
  40. // istanbul ignore next: this is actually an abstract method but we need a placeholder to get `function.length`
  41. validate(_value, _utils) {
  42. return false;
  43. }
  44. deprecated(_value, _utils) {
  45. return false;
  46. }
  47. forward(_value, _utils) {
  48. return undefined;
  49. }
  50. redirect(_value, _utils) {
  51. return undefined;
  52. }
  53. overlap(currentValue, _newValue, _utils) {
  54. return currentValue;
  55. }
  56. preprocess(value, _utils) {
  57. return value;
  58. }
  59. postprocess(value, _utils) {
  60. return value;
  61. }
  62. }
  63. exports.Schema = Schema;
  64. function normalizeHandler(handler, superSchema, handlerArgumentsLength) {
  65. return typeof handler === 'function'
  66. ? (...args) => handler(...args.slice(0, handlerArgumentsLength - 1), superSchema, ...args.slice(handlerArgumentsLength - 1))
  67. : () => handler;
  68. }