message.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. var messageOptions = require("./message-options");
  2. function Message(raw) {
  3. if (!(this instanceof Message)) {
  4. return new Message(raw);
  5. }
  6. this.params = cleanParams(raw || {});
  7. }
  8. function cleanParams(raw) {
  9. var params = {};
  10. Object.keys(raw).forEach(function(param) {
  11. if(messageOptions[param]) {
  12. params[param] = raw[param];
  13. }
  14. });
  15. return params;
  16. }
  17. Message.prototype.addNotification = function() {
  18. return handleParamSet.call(this, arguments, "notification");
  19. };
  20. function handleParamSet(args, paramType) {
  21. if(args.length == 1) {
  22. return setParam.call(this, paramType, args[0]);
  23. }
  24. if(args.length == 2) {
  25. return addParam.call(this, paramType, args[0], args[1]);
  26. }
  27. throw new Error("Invalid number of arguments given to for setting " + paramType + " (" + args.length + ")");
  28. }
  29. function setParam(paramType, obj) {
  30. if (typeof obj === 'object' && Object.keys(obj).length > 0) {
  31. this.params[paramType] = obj;
  32. }
  33. }
  34. function addParam(paramType, key, value) {
  35. if(!this.params[paramType]) {
  36. this.params[paramType] = {};
  37. }
  38. return this.params[paramType][key] = value;
  39. }
  40. Message.prototype.addData = function() {
  41. return handleParamSet.call(this, arguments, "data");
  42. };
  43. Message.prototype.toJson = function() {
  44. var json = {};
  45. Object.keys(this.params).forEach(function(param) {
  46. var optionDescription = messageOptions[param];
  47. if(!optionDescription) {
  48. return;
  49. }
  50. var key = optionDescription.__argName || param;
  51. json[key] = this.params[param];
  52. }.bind(this));
  53. return json;
  54. };
  55. /** DEPRECATED */
  56. Message.prototype.addDataWithKeyValue = function (key, value) {
  57. console.warn("Message#addDataWithKeyValue has been deprecated. Please use Message#addData instead.");
  58. this.addData(key, value);
  59. };
  60. Message.prototype.addDataWithObject = function (obj) {
  61. console.warn("Message#addDataWithObject has been deprecated. Please use Message#addData instead.");
  62. this.addData(obj);
  63. };
  64. /** END DEPRECATED */
  65. module.exports = Message;