filo_caspar/app/controller/store.js

63 lines
1.2 KiB
JavaScript
Raw Normal View History

2016-04-14 04:01:51 +00:00
const _ = require('lodash')
2016-04-10 08:37:05 +00:00
const socket = require('../socket')
const storage = {}
const events = {}
2016-04-14 04:01:51 +00:00
// Listen on all events
let onevent = socket.onevent
2016-04-10 08:37:05 +00:00
2016-04-14 04:01:51 +00:00
socket.onevent = function(packet) {
let args = packet.data || []
onevent.call(this, packet) // original call
packet.data = ['*'].concat(args)
onevent.call(this, packet)
}
2016-04-10 08:37:05 +00:00
2016-04-14 04:01:51 +00:00
function genId(name, id) {
if (id) {
return `${name}:${id}`
}
return name
}
2016-04-10 08:37:05 +00:00
2016-04-14 04:01:51 +00:00
const store = {
get: function(name, id) {
return storage[genId(name, id)]
2016-04-10 08:37:05 +00:00
},
2016-04-14 04:01:51 +00:00
listen: function(name, caller, id) {
events[genId(name, id)] = caller
2016-04-10 08:37:05 +00:00
},
unlisten: function(name) {
delete events[name]
2016-04-14 04:01:51 +00:00
delete storage[name]
2016-04-10 08:37:05 +00:00
},
2016-04-14 04:01:51 +00:00
events: events,
storage: storage,
2016-04-10 08:37:05 +00:00
}
2016-04-14 04:01:51 +00:00
socket.on('*', (event, data) => {
let name = genId(event, data && data.id)
if (events[name]) {
storage[name] = data
events[name]()
}
2016-04-14 13:22:27 +00:00
if (event.indexOf('single') >= 0) {
2016-04-14 04:01:51 +00:00
let check = event.replace('single', 'all')
if (events[name]) {
let index = _.findIndex(storage[check], { id: data.id })
if (index > -1) {
storage[check][index] = data
events[name]()
}
}
}
2016-04-10 08:37:05 +00:00
})
2016-04-14 04:01:51 +00:00
window.store = store
2016-04-10 08:37:05 +00:00
module.exports = store