blob: 1ed8a205664c7ecf6d9dbc9fb036fa3caf28fb7e [file] [log] [blame]
Matteo Scandoloe3ed0162016-12-01 10:09:12 -08001(function () {
2 'use strict';
3
4 const socketIo = require('./websocket.js');
Matteo Scandolo606751e2017-01-13 13:07:02 -08005 const config = require('../config/config.js');
Matteo Scandoloe3ed0162016-12-01 10:09:12 -08006 const logger = require('../config/logger.js');
Matteo Scandolo606751e2017-01-13 13:07:02 -08007 const request = require('superagent');
Matteo Scandoloe3ed0162016-12-01 10:09:12 -08008 const socket = socketIo.get();
Matteo Scandolo606751e2017-01-13 13:07:02 -08009 const _ = require('lodash');
Matteo Scandoloe3ed0162016-12-01 10:09:12 -080010
11 var redis = require('redis');
12 var client = redis.createClient({
Matteo Scandolo606751e2017-01-13 13:07:02 -080013 host: config.redis.host,
14 port: config.redis.port
Matteo Scandoloe3ed0162016-12-01 10:09:12 -080015 });
16
17 client.on('error', function (err) {
18 logger.log('error', err);
19 });
20
21 client.on('ready', function () {
22 logger.log('info', 'Redis connected');
23 });
24
25 client.on('subscribe', function (channel) {
26 logger.log('debug', `Subscribed to channel: ${channel}`);
27 });
28
29 client.on('message', function (channel, message) {
Matteo Scandolof05d8a62016-12-06 13:36:49 -080030 logger.log('warn', 'sub channel ' + channel + ': ' + message);
Matteo Scandoloe3ed0162016-12-01 10:09:12 -080031
32 let msg;
33 try {
34 msg = JSON.parse(message);
35 // TODO find the user that needs to be notified for msg.object update
36 socket.emit('event', {model: channel, msg: msg});
37 }
38 catch(e) {
39 // send the event also if it is not JSON
40 msg = message;
41 socket.emit('event', {model: channel, msg: msg});
42 }
Matteo Scandoloe3ed0162016-12-01 10:09:12 -080043 });
44
Matteo Scandolo606751e2017-01-13 13:07:02 -080045 // dynamically load Model names to listen on channels
46 // NOTE how to listen for models defined by services?
47 request.get(`${config.xos.host}:${config.xos.port}/api/utility/modeldefs`)
48 .end((err, res) => {
49 if (err) {
50 logger.log('error', err);
51 }
52 if (res) {
53 const models = _.map(res.body, i => i.name);
54 _.forEach(models, c => {
55 client.subscribe(c);
56 });
57 }
Matteo Scandoloe3ed0162016-12-01 10:09:12 -080058 });
Matteo Scandolo606751e2017-01-13 13:07:02 -080059
Matteo Scandoloe3ed0162016-12-01 10:09:12 -080060})();