Initial commit
This commit is contained in:
41
static/subscription.mjs
Normal file
41
static/subscription.mjs
Normal file
@@ -0,0 +1,41 @@
|
||||
|
||||
export class Subscription_Endpoint extends EventTarget {
|
||||
|
||||
async connect(path) {
|
||||
const wsProtocol = location.protocol === 'https:' ? 'wss:' : 'ws:';
|
||||
const wsUrl = `${wsProtocol}//${location.host}${path}`;
|
||||
|
||||
const ws = new WebSocket(wsUrl);
|
||||
|
||||
await new Promise((resolve, reject) => {
|
||||
ws.addEventListener('open', resolve, { once: true });
|
||||
ws.addEventListener('error', reject, { once: true });
|
||||
});
|
||||
|
||||
ws.addEventListener('message', ev => {
|
||||
this.dispatchEvent(new CustomEvent('message', { detail: ev.data }));
|
||||
});
|
||||
|
||||
ws.addEventListener('close', () => {
|
||||
this.dispatchEvent(new Event('close'));
|
||||
});
|
||||
|
||||
ws.addEventListener('error', err => {
|
||||
this.dispatchEvent(new CustomEvent('error', { detail: err }));
|
||||
});
|
||||
|
||||
this.ws = ws;
|
||||
return ws;
|
||||
}
|
||||
|
||||
subscribe(resource) {
|
||||
const { ws } = this;
|
||||
ws.send(JSON.stringify({
|
||||
cmd: 'subscribe',
|
||||
resource
|
||||
}));
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user