builder.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. var util = require('../util');
  2. function JsonBuilder() { }
  3. JsonBuilder.prototype.build = function(value, shape) {
  4. return JSON.stringify(translate(value, shape));
  5. };
  6. function translate(value, shape) {
  7. if (!shape || value === undefined || value === null) return undefined;
  8. switch (shape.type) {
  9. case 'structure': return translateStructure(value, shape);
  10. case 'map': return translateMap(value, shape);
  11. case 'list': return translateList(value, shape);
  12. default: return translateScalar(value, shape);
  13. }
  14. }
  15. function translateStructure(structure, shape) {
  16. if (shape.isDocument) {
  17. return structure;
  18. }
  19. var struct = {};
  20. util.each(structure, function(name, value) {
  21. var memberShape = shape.members[name];
  22. if (memberShape) {
  23. if (memberShape.location !== 'body') return;
  24. var locationName = memberShape.isLocationName ? memberShape.name : name;
  25. var result = translate(value, memberShape);
  26. if (result !== undefined) struct[locationName] = result;
  27. }
  28. });
  29. return struct;
  30. }
  31. function translateList(list, shape) {
  32. var out = [];
  33. util.arrayEach(list, function(value) {
  34. var result = translate(value, shape.member);
  35. if (result !== undefined) out.push(result);
  36. });
  37. return out;
  38. }
  39. function translateMap(map, shape) {
  40. var out = {};
  41. util.each(map, function(key, value) {
  42. var result = translate(value, shape.value);
  43. if (result !== undefined) out[key] = result;
  44. });
  45. return out;
  46. }
  47. function translateScalar(value, shape) {
  48. return shape.toWireFormat(value);
  49. }
  50. /**
  51. * @api private
  52. */
  53. module.exports = JsonBuilder;