You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

80 lines
2.1 KiB

4 years ago
  1. 'use strict';
  2. module.exports = function defFunc (ajv) {
  3. var transform = {
  4. trimLeft: function (value) {
  5. return value.replace(/^[\s]+/, '');
  6. },
  7. trimRight: function (value) {
  8. return value.replace(/[\s]+$/, '');
  9. },
  10. trim: function (value) {
  11. return value.trim();
  12. },
  13. toLowerCase: function (value) {
  14. return value.toLowerCase();
  15. },
  16. toUpperCase: function (value) {
  17. return value.toUpperCase();
  18. },
  19. toEnumCase: function (value, cfg) {
  20. return cfg.hash[makeHashTableKey(value)] || value;
  21. }
  22. };
  23. defFunc.definition = {
  24. type: 'string',
  25. errors: false,
  26. modifying: true,
  27. valid: true,
  28. compile: function (schema, parentSchema) {
  29. var cfg;
  30. if (schema.indexOf('toEnumCase') !== -1) {
  31. // build hash table to enum values
  32. cfg = {hash: {}};
  33. // requires `enum` in schema
  34. if (!parentSchema.enum)
  35. throw new Error('Missing enum. To use `transform:["toEnumCase"]`, `enum:[...]` is required.');
  36. for (var i = parentSchema.enum.length; i--; i) {
  37. var v = parentSchema.enum[i];
  38. if (typeof v !== 'string') continue;
  39. var k = makeHashTableKey(v);
  40. // requires all `enum` values have unique keys
  41. if (cfg.hash[k])
  42. throw new Error('Invalid enum uniqueness. To use `transform:["toEnumCase"]`, all values must be unique when case insensitive.');
  43. cfg.hash[k] = v;
  44. }
  45. }
  46. return function (data, dataPath, object, key) {
  47. // skip if value only
  48. if (!object) return;
  49. // apply transform in order provided
  50. for (var j = 0, l = schema.length; j < l; j++)
  51. data = transform[schema[j]](data, cfg);
  52. object[key] = data;
  53. };
  54. },
  55. metaSchema: {
  56. type: 'array',
  57. items: {
  58. type: 'string',
  59. enum: [
  60. 'trimLeft', 'trimRight', 'trim',
  61. 'toLowerCase', 'toUpperCase', 'toEnumCase'
  62. ]
  63. }
  64. }
  65. };
  66. ajv.addKeyword('transform', defFunc.definition);
  67. return ajv;
  68. function makeHashTableKey (value) {
  69. return value.toLowerCase();
  70. }
  71. };