dynamicDefaults.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. 'use strict';
  2. var sequences = {};
  3. var DEFAULTS = {
  4. timestamp: function() { return Date.now(); },
  5. datetime: function() { return (new Date).toISOString(); },
  6. date: function() { return (new Date).toISOString().slice(0, 10); },
  7. time: function() { return (new Date).toISOString().slice(11); },
  8. random: function() { return Math.random(); },
  9. randomint: function (args) {
  10. var limit = args && args.max || 2;
  11. return function() { return Math.floor(Math.random() * limit); };
  12. },
  13. seq: function (args) {
  14. var name = args && args.name || '';
  15. sequences[name] = sequences[name] || 0;
  16. return function() { return sequences[name]++; };
  17. }
  18. };
  19. module.exports = function defFunc(ajv) {
  20. defFunc.definition = {
  21. compile: function (schema, parentSchema, it) {
  22. var funcs = {};
  23. for (var key in schema) {
  24. var d = schema[key];
  25. var func = getDefault(typeof d == 'string' ? d : d.func);
  26. funcs[key] = func.length ? func(d.args) : func;
  27. }
  28. return it.opts.useDefaults && !it.compositeRule
  29. ? assignDefaults
  30. : noop;
  31. function assignDefaults(data) {
  32. for (var prop in schema){
  33. if (data[prop] === undefined
  34. || (it.opts.useDefaults == 'empty'
  35. && (data[prop] === null || data[prop] === '')))
  36. data[prop] = funcs[prop]();
  37. }
  38. return true;
  39. }
  40. function noop() { return true; }
  41. },
  42. DEFAULTS: DEFAULTS,
  43. metaSchema: {
  44. type: 'object',
  45. additionalProperties: {
  46. type: ['string', 'object'],
  47. additionalProperties: false,
  48. required: ['func', 'args'],
  49. properties: {
  50. func: { type: 'string' },
  51. args: { type: 'object' }
  52. }
  53. }
  54. }
  55. };
  56. ajv.addKeyword('dynamicDefaults', defFunc.definition);
  57. return ajv;
  58. function getDefault(d) {
  59. var def = DEFAULTS[d];
  60. if (def) return def;
  61. throw new Error('invalid "dynamicDefaults" keyword property value: ' + d);
  62. }
  63. };