core
Version:
Core Libs
121 lines (94 loc) • 3.02 kB
JavaScript
var EventDispatcher = require('../../event/EventDispatcher').EventDispatcher;
var RbmqMessage = function(body, params) {
EventDispatcher.call(this);
this._body = body;
this._data = {};
if (params && typeof params == 'object' && params.constructor == Object) {
var methodName, key, value;
for (key in RbmqMessage.Attributes) {
if (params.hasOwnProperty(key)) {
value = params[key];
} else {
value = RbmqMessage.Attributes[key];
}
methodName = key.charAt(0).toUpperCase() + key.substr(1);
if (typeof this['set' + methodName] == 'function') {
RbmqMessage.prototype['set' + methodName].call(this, value);
}
}
}
};
RbmqMessage.Attributes = {
'routingKey': undefined,
'headers': {},
'mandatory': false,
'immediate': false,
'contentEncoding': undefined,
'contentType': undefined,
'deliveryMode': undefined,
'appId': undefined,
'userId': undefined,
'messageId': undefined,
'expiration': undefined,
'priority': undefined
};
RbmqMessage.prototype = Object.create(EventDispatcher.prototype);
Object.keys(RbmqMessage.Attributes).forEach(function(key) {
var methodName = key.charAt(0).toUpperCase() + key.substr(1);
RbmqMessage.prototype['set' + methodName] = function(value) {
this._data[key] = value;
return this;
};
RbmqMessage.prototype['get' + methodName] = function() {
return this._data[key];
};
});
RbmqMessage.prototype.getBody = function() {
return this._body;
};
RbmqMessage.prototype.setBody = function(value) {
this._body = value;
return this;
};
RbmqMessage.prototype.getBodySize = function() {
if (this._body instanceof Buffer) {
return this._body.length;
} else {
return new Buffer(JSON.stringify(this._body)).length;
}
};
RbmqMessage.prototype.getSize = function() {
return this.getBodySize() + (new Buffer(JSON.stringify(this._data)).length);
};
RbmqMessage.prototype.hasHeader = function(name) {
return this._data.headers.hasOwnProperty(name);
};
RbmqMessage.prototype.removeHeader = function(name) {
if (this.hasHeader(name)) {
delete this._data.headers[name];
}
};
RbmqMessage.prototype.getHeader = function(name, defaultValue) {
if (!this.hasHeader(name)) {
return defaultValue;
}
return this._data.headers[name];
};
RbmqMessage.prototype.getArguments = function() {
var args = JSON.parse(JSON.stringify(this._data));
if (args.routingKey) {
delete args.routingKey;
}
for (var key in Object.keys(args)) {
if (args[key] === undefined) {
delete args[key];
}
}
return args;
};
RbmqMessage.Options = {};
/* Delivery mode non-persistant */
RbmqMessage.Options.DMODE_NON_PERSISTENT = 1;
/* Delivery mode persistant */
RbmqMessage.Options.DMODE_PERSISTENT = 2;
exports.RbmqMessage = RbmqMessage;