forked from resgateio/resgate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tickerService.js
35 lines (30 loc) · 1.1 KB
/
tickerService.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// Connect to NATS server
const nats = require('nats').connect("nats://localhost:4222");
let model = { seconds: 0 };
// Get listener. Reply with the json encoded model
nats.subscribe('get.ticker.model', function(req, reply) {
nats.publish(reply, JSON.stringify({ result: { model: model }}));
});
// Access listener. Only get access if the token has any role set
nats.subscribe('access.ticker.model', (req, reply) => {
let { token } = JSON.parse(req);
if (token && token.role) {
nats.publish(reply, JSON.stringify({ result: { get: true }}));
} else {
nats.publish(reply, JSON.stringify({ result: { get: false }}));
}
});
// Recursive counter that updates the model and sends a change event every second
let count = function() {
setTimeout(() => {
model.seconds++;
nats.publish('event.ticker.model.change', JSON.stringify({
values: { seconds: model.seconds }
}));
count();
}, 1000);
};
count();
// System resets tells Resgate that the service has been (re)started.
// Resgate will then update any cached resource from ticker
nats.publish('system.reset', JSON.stringify({ resources: [ 'ticker.>' ] }));