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.

72 lines
2.0 KiB

4 years ago
  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. };