redux-devtools/packages/redux-devtools-cli/src/worker.ts

87 lines
2.5 KiB
TypeScript
Raw Normal View History

import SCWorker from 'socketcluster/scworker';
import express from 'express';
import routes from './routes';
import createStore from './store';
const app = express();
2019-01-04 01:30:48 +03:00
class Worker extends SCWorker {
run() {
const httpServer = this.httpServer;
const scServer = this.scServer;
const options = this.options;
const store = createStore(options);
2019-01-04 01:30:48 +03:00
httpServer.on('request', app);
2019-01-08 19:35:12 +03:00
app.use(routes(options, store, scServer));
2019-01-04 01:30:48 +03:00
scServer.addMiddleware(scServer.MIDDLEWARE_EMIT, function (req, next) {
const channel = req.event;
const data = req.data;
2019-01-10 21:51:14 +03:00
if (
channel.substr(0, 3) === 'sc-' ||
channel === 'respond' ||
channel === 'log'
) {
2019-01-04 01:30:48 +03:00
scServer.exchange.publish(channel, data);
} else if (channel === 'log-noid') {
2019-01-10 21:51:14 +03:00
scServer.exchange.publish('log', { id: req.socket.id, data: data });
2019-01-04 01:30:48 +03:00
}
next();
});
scServer.addMiddleware(scServer.MIDDLEWARE_SUBSCRIBE, function (req, next) {
2019-01-04 01:30:48 +03:00
next();
if (req.channel === 'report') {
2019-01-10 21:51:14 +03:00
store
.list()
.then(function (data) {
req.socket.emit(req.channel!, { type: 'list', data: data });
2019-01-10 21:51:14 +03:00
})
.catch(function (error) {
2019-01-10 21:51:14 +03:00
console.error(error); // eslint-disable-line no-console
});
2019-01-04 01:30:48 +03:00
}
});
scServer.on('connection', function (socket) {
let channelToWatch: string, channelToEmit: string;
socket.on('login', function (this: Worker, credentials, respond) {
2019-01-04 01:30:48 +03:00
if (credentials === 'master') {
channelToWatch = 'respond';
channelToEmit = 'log';
} else {
channelToWatch = 'log';
channelToEmit = 'respond';
}
this.exchange.subscribe('sc-' + socket.id).watch(function (msg) {
2019-01-04 01:30:48 +03:00
socket.emit(channelToWatch, msg);
});
respond(null, channelToWatch);
});
socket.on('getReport', function (id, respond) {
2019-01-10 21:51:14 +03:00
store
.get(id)
.then(function (data) {
2019-01-10 21:51:14 +03:00
respond(null, data);
})
.catch(function (error) {
2019-01-10 21:51:14 +03:00
console.error(error); // eslint-disable-line no-console
});
2019-01-04 01:30:48 +03:00
});
socket.on('disconnect', function (this: Worker) {
const channel = this.exchange.channel('sc-' + socket.id);
2019-01-04 01:30:48 +03:00
channel.unsubscribe();
channel.destroy();
2019-01-10 21:51:14 +03:00
scServer.exchange.publish(channelToEmit, {
id: socket.id,
type: 'DISCONNECTED',
2019-01-10 21:51:14 +03:00
});
2019-01-04 01:30:48 +03:00
});
});
2019-01-10 21:51:14 +03:00
}
2019-01-04 01:30:48 +03:00
}
new Worker();