UI for Zipcoin Blue

dynamicDefaults.js 1.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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) data[prop] = funcs[prop]();
  34. return true;
  35. }
  36. function noop() { return true; }
  37. },
  38. DEFAULTS: DEFAULTS,
  39. metaSchema: {
  40. type: 'object',
  41. additionalProperties: {
  42. type: ['string', 'object'],
  43. additionalProperties: false,
  44. required: ['func', 'args'],
  45. properties: {
  46. func: { type: 'string' },
  47. args: { type: 'object' }
  48. }
  49. }
  50. }
  51. };
  52. ajv.addKeyword('dynamicDefaults', defFunc.definition);
  53. return ajv;
  54. function getDefault(d) {
  55. var def = DEFAULTS[d];
  56. if (def) return def;
  57. throw new Error('invalid "dynamicDefaults" keyword property value: ' + d);
  58. }
  59. };