sails-rabbitmq
Version:
sails-rabbitmq adapter for Sails / Waterline
102 lines (84 loc) • 3.27 kB
JavaScript
;
Object.defineProperty(exports, '__esModule', {
value: true
});
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
var rabbit = require('rabbit.js');
var _ = require('lodash');
var Persister = (function () {
function Persister(sailsApp) {
_classCallCheck(this, Persister);
this.sails = sailsApp;
this.sockets = {};
}
_createClass(Persister, [{
key: 'initialize',
/**
* Bind all relevant models to persistence handlers
*/
value: function initialize(next) {
var _this = this;
Promise.all(_.map(this.getPersistentModels(), function (Model) {
return Model.socket({ type: 'worker', worker: 'persistence' }).then(function (socket) {
_this.bindPersistenceHandler(socket, Model);
});
})).then(function () {
next();
})['catch'](next);
}
}, {
key: 'teardown',
/**
* Release all sockets
*/
value: function teardown(next) {
_.each(this.sockets, function (socket) {
socket.close();
});
this.sockets = {};
}
}, {
key: 'bindPersistenceHandler',
value: function bindPersistenceHandler(socket, Model) {
this.sockets[model.identity] = socket;
socket.on('data', function (data) {
var values = JSON.parse(data);
var pk = values[Model.primaryKey];
if (pk) {
Model.update(values).then(function (model) {});
} else {
Model.create(values).then(function (model) {});
}
});
}
}, {
key: 'getRabbitConnections',
/**
* Get all sails connections that use the sails-rabbitmq adapter
*/
value: function getRabbitConnections() {
var rabbitConnections = _.pick(this.sails.config.connections, function (connection) {
return connection.adapter == 'sails-rabbitmq';
});
return _.keys(rabbitConnections);
}
}, {
key: 'getPersistentModels',
/**
* Find all sails models that meet the following conditions:
* 1. use the sails-rabbitmq adapter in its connection
* 2. contain a persistence connection
* 3. implement the socket() function (via the adapter)
*/
value: function getPersistentModels() {
var rabbitConnections = this.getRabbitConnections();
return _.pick(this.sails.models, function (model) {
return _.all([model.connection.length > 1, _.intersection(model.connection, rabbitConnections).length, _.isFunction(model.socket)]);
});
}
}]);
return Persister;
})();
exports['default'] = Persister;
module.exports = exports['default'];