transform.js 2.2 KB

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