parser.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. var util = require('../util');
  2. function JsonParser() { }
  3. JsonParser.prototype.parse = function(value, shape) {
  4. return translate(JSON.parse(value), shape);
  5. };
  6. function translate(value, shape) {
  7. if (!shape || value === undefined) 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 (structure == null) return undefined;
  17. if (shape.isDocument) return structure;
  18. var struct = {};
  19. var shapeMembers = shape.members;
  20. var isAwsQueryCompatible = shape.api && shape.api.awsQueryCompatible;
  21. util.each(shapeMembers, function(name, memberShape) {
  22. var locationName = memberShape.isLocationName ? memberShape.name : name;
  23. if (Object.prototype.hasOwnProperty.call(structure, locationName)) {
  24. var value = structure[locationName];
  25. var result = translate(value, memberShape);
  26. if (result !== undefined) struct[name] = result;
  27. } else if (isAwsQueryCompatible && memberShape.defaultValue) {
  28. if (memberShape.type === 'list') {
  29. struct[name] = typeof memberShape.defaultValue === 'function' ? memberShape.defaultValue() : memberShape.defaultValue;
  30. }
  31. }
  32. });
  33. return struct;
  34. }
  35. function translateList(list, shape) {
  36. if (list == null) return undefined;
  37. var out = [];
  38. util.arrayEach(list, function(value) {
  39. var result = translate(value, shape.member);
  40. if (result === undefined) out.push(null);
  41. else out.push(result);
  42. });
  43. return out;
  44. }
  45. function translateMap(map, shape) {
  46. if (map == null) return undefined;
  47. var out = {};
  48. util.each(map, function(key, value) {
  49. var result = translate(value, shape.value);
  50. if (result === undefined) out[key] = null;
  51. else out[key] = result;
  52. });
  53. return out;
  54. }
  55. function translateScalar(value, shape) {
  56. return shape.toType(value);
  57. }
  58. /**
  59. * @api private
  60. */
  61. module.exports = JsonParser;