receptor/src/socket.js

67 lines
1.5 KiB
JavaScript
Raw Normal View History

import { dispatch } from './store';
import { subscribe } from './actions/subscribe';
let ws;
let serial = 0;
let transactions = {};
2017-09-08 09:35:12 +02:00
let connected = false;
let queue = [];
2017-10-13 06:34:26 +02:00
const getURI = ({ uri, password }) => `${uri}${password ?
`?password=${encodeURIComponent(password)}` : ''}`;
export default function ws_send(type, body, callback = null) {
const _serial = serial++;
if (callback) {
transactions[_serial] = callback;
}
const obj = {
type,
serial: _serial,
...body
};
const msg = JSON.stringify(obj);
console.log("->", type, obj);
2017-09-08 09:35:12 +02:00
if (!connected) {
queue.push(msg);
} else {
ws.send(msg);
}
return _serial;
}
const handlers = {
RESOURCES_EXTANT: msg => dispatch(subscribe(...msg.ids)),
2017-09-08 10:27:00 +02:00
UPDATE_RESOURCES: msg => dispatch(msg),
RESOURCES_REMOVED: msg => dispatch(msg),
};
function ws_recv(e) {
const msg = JSON.parse(e.data);
console.log("<-", msg.type, msg);
const cb = transactions[msg.serial];
cb && cb(msg);
const handler = handlers[msg.type];
handler && handler(msg);
}
2017-09-08 06:55:47 +02:00
export function ws_init(uri, open, close) {
2017-10-13 06:34:26 +02:00
ws = new WebSocket(getURI(uri));
2017-09-08 09:35:12 +02:00
ws.addEventListener("open", () => {
connected = true;
open.apply(this, arguments);
while (queue.length > 0) {
ws.send(queue.pop());
}
});
ws.addEventListener("message", ws_recv);
2017-09-08 09:35:12 +02:00
ws.addEventListener("close", () => {
connected = false;
close.apply(this, arguments);
});
}
2017-09-08 07:07:31 +02:00
export function ws_disconnect() {
ws.close();
}