Skip to content

Instantly share code, notes, and snippets.

@AGhost-7
Created January 5, 2016 18:07
Show Gist options
  • Select an option

  • Save AGhost-7/50b8a602631c95417aec to your computer and use it in GitHub Desktop.

Select an option

Save AGhost-7/50b8a602631c95417aec to your computer and use it in GitHub Desktop.
Use publish/subscribe with database persistence to cache on the application server (high read data)
// In some situations, you want the "configuration" to be persistent and dynamic. For example, a
// web site with dynamic forms.
// There are multiple ways of making this work...
// - Store it in the database and access it when you need it; very poor performance.
// - Store it in the database and cache the data directly in the application server. Update
// every now and then; better performance, but not very clean considering you will need to wait
// for the configuration changes to take effect.
// - Use pud/sub; best performance and changes are instantaneous.
function reactiveDataPool(seneca, pgClient, entityName, query, done) {
var pushAll = function(arr, items) {
for(var i = 0; i < items.length; i++) arr.push(item[i]);
};
var indexOfId = function(arr, id) {
for(var i = 0; i < arr.length; i++) {
if(arr[i].id === id) return i;
}
return -1;
};
var pool = [];
// initial load of the data from the DB.
seneca
.make(entityName)
.load$(query, function(err, ents) {
if(err) return done(err);
pushAll(pool, ents);
// create the names for the events.
var snake = _.snakeCase(entityName);
var delEv = 'delete_' + snake;
var addEv = 'add_' + snake;
var updateEv = 'update_' + snake;
pgClient.on('notification', function(msg) {
var data = JSON.parse(msg.payload);
var event = msg.channel;
if(event === addEv) {
pool.push(data);
} else if(event === delEv) {
var i = indexOfId(pool, data.id);
pool.splice(i, 1);
} else if(event === updateEv) {
var i = indexOfId(pool, data.id);
pool[i] = data;
}
});
[delEv, addEv, updateEv].forEach(function(event) {
pgClient.query('LISTEN ' + event);
});
done(null, pool);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment