set.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. var util = require('../core').util;
  2. var typeOf = require('./types').typeOf;
  3. /**
  4. * @api private
  5. */
  6. var memberTypeToSetType = {
  7. 'String': 'String',
  8. 'Number': 'Number',
  9. 'NumberValue': 'Number',
  10. 'Binary': 'Binary'
  11. };
  12. /**
  13. * @api private
  14. */
  15. var DynamoDBSet = util.inherit({
  16. constructor: function Set(list, options) {
  17. options = options || {};
  18. this.wrapperName = 'Set';
  19. this.initialize(list, options.validate);
  20. },
  21. initialize: function(list, validate) {
  22. var self = this;
  23. self.values = [].concat(list);
  24. self.detectType();
  25. if (validate) {
  26. self.validate();
  27. }
  28. },
  29. detectType: function() {
  30. this.type = memberTypeToSetType[typeOf(this.values[0])];
  31. if (!this.type) {
  32. throw util.error(new Error(), {
  33. code: 'InvalidSetType',
  34. message: 'Sets can contain string, number, or binary values'
  35. });
  36. }
  37. },
  38. validate: function() {
  39. var self = this;
  40. var length = self.values.length;
  41. var values = self.values;
  42. for (var i = 0; i < length; i++) {
  43. if (memberTypeToSetType[typeOf(values[i])] !== self.type) {
  44. throw util.error(new Error(), {
  45. code: 'InvalidType',
  46. message: self.type + ' Set contains ' + typeOf(values[i]) + ' value'
  47. });
  48. }
  49. }
  50. },
  51. /**
  52. * Render the underlying values only when converting to JSON.
  53. */
  54. toJSON: function() {
  55. var self = this;
  56. return self.values;
  57. }
  58. });
  59. /**
  60. * @api private
  61. */
  62. module.exports = DynamoDBSet;