translator.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. var util = require('../core').util;
  2. var convert = require('./converter');
  3. var Translator = function(options) {
  4. options = options || {};
  5. this.attrValue = options.attrValue;
  6. this.convertEmptyValues = Boolean(options.convertEmptyValues);
  7. this.wrapNumbers = Boolean(options.wrapNumbers);
  8. };
  9. Translator.prototype.translateInput = function(value, shape) {
  10. this.mode = 'input';
  11. return this.translate(value, shape);
  12. };
  13. Translator.prototype.translateOutput = function(value, shape) {
  14. this.mode = 'output';
  15. return this.translate(value, shape);
  16. };
  17. Translator.prototype.translate = function(value, shape) {
  18. var self = this;
  19. if (!shape || value === undefined) return undefined;
  20. if (shape.shape === self.attrValue) {
  21. return convert[self.mode](value, {
  22. convertEmptyValues: self.convertEmptyValues,
  23. wrapNumbers: self.wrapNumbers,
  24. });
  25. }
  26. switch (shape.type) {
  27. case 'structure': return self.translateStructure(value, shape);
  28. case 'map': return self.translateMap(value, shape);
  29. case 'list': return self.translateList(value, shape);
  30. default: return self.translateScalar(value, shape);
  31. }
  32. };
  33. Translator.prototype.translateStructure = function(structure, shape) {
  34. var self = this;
  35. if (structure == null) return undefined;
  36. var struct = {};
  37. util.each(structure, function(name, value) {
  38. var memberShape = shape.members[name];
  39. if (memberShape) {
  40. var result = self.translate(value, memberShape);
  41. if (result !== undefined) struct[name] = result;
  42. }
  43. });
  44. return struct;
  45. };
  46. Translator.prototype.translateList = function(list, shape) {
  47. var self = this;
  48. if (list == null) return undefined;
  49. var out = [];
  50. util.arrayEach(list, function(value) {
  51. var result = self.translate(value, shape.member);
  52. if (result === undefined) out.push(null);
  53. else out.push(result);
  54. });
  55. return out;
  56. };
  57. Translator.prototype.translateMap = function(map, shape) {
  58. var self = this;
  59. if (map == null) return undefined;
  60. var out = {};
  61. util.each(map, function(key, value) {
  62. var result = self.translate(value, shape.value);
  63. if (result === undefined) out[key] = null;
  64. else out[key] = result;
  65. });
  66. return out;
  67. };
  68. Translator.prototype.translateScalar = function(value, shape) {
  69. return shape.toType(value);
  70. };
  71. /**
  72. * @api private
  73. */
  74. module.exports = Translator;