summaryrefslogtreecommitdiff
path: root/src/api
diff options
context:
space:
mode:
authorHaishan <[email protected]>2019-11-08 00:40:48 +0800
committerHaishan <[email protected]>2019-11-09 13:21:25 +0800
commit6754620d7abfb7273cff5f173349eb507fc0c8b7 (patch)
treed91136e4863b4c41ff521bf182dd8cc08bb355bc /src/api
parent130793446476e47b2e5f0457482dfbfdf1944b48 (diff)
feat: connections inspection
Diffstat (limited to 'src/api')
-rw-r--r--src/api/connections.js51
1 files changed, 51 insertions, 0 deletions
diff --git a/src/api/connections.js b/src/api/connections.js
new file mode 100644
index 0000000..594fc5e
--- /dev/null
+++ b/src/api/connections.js
@@ -0,0 +1,51 @@
+const endpoint = '/connections';
+
+let fetched = false;
+let subscribers = [];
+
+function appendData(s) {
+ let o;
+ try {
+ o = JSON.parse(s);
+ } catch (err) {
+ // eslint-disable-next-line no-console
+ console.log('JSON.parse error', JSON.parse(s));
+ }
+ subscribers.forEach(f => f(o));
+}
+
+function getWsUrl(apiConfig) {
+ const { hostname, port, secret } = apiConfig;
+ let qs = '';
+ if (typeof secret === 'string' && secret !== '') {
+ qs += '?token=' + secret;
+ }
+ return `ws://${hostname}:${port}${endpoint}${qs}`;
+}
+
+let wsState;
+function fetchData(apiConfig, listener) {
+ if (fetched || wsState === 1) {
+ if (listener) return subscribe(listener);
+ }
+ wsState = 1;
+ const url = getWsUrl(apiConfig);
+ const ws = new WebSocket(url);
+ ws.addEventListener('error', function(_ev) {
+ wsState = 3;
+ });
+ ws.addEventListener('message', function(event) {
+ appendData(event.data);
+ });
+ if (listener) return subscribe(listener);
+}
+
+function subscribe(listener) {
+ subscribers.push(listener);
+ return function unsubscribe() {
+ const idx = subscribers.indexOf(listener);
+ subscribers.splice(idx, 1);
+ };
+}
+
+export { fetchData };