33 lines
1003 B
TypeScript
33 lines
1003 B
TypeScript
import { browser } from '$app/environment';
|
|
import { writable, get } from 'svelte/store';
|
|
import ReconnectingWebSocket from 'reconnecting-websocket';
|
|
export const messages = writable([]);
|
|
export const handlers = writable({})
|
|
export const events = writable([])
|
|
export const connect = (url,) => {
|
|
if (!browser) return {send: (e)=>{}, close: (e)=>{}};
|
|
const ws = new ReconnectingWebSocket(url);
|
|
|
|
ws.onmessage = (m) => {
|
|
|
|
messages.update((o) => [JSON.parse(m.data), ...o]);
|
|
Object.values(get(handlers)).map(h => {
|
|
if(h ==null)return
|
|
h(JSON.parse(m.data));
|
|
})
|
|
};
|
|
ws.onopen = (e) => {
|
|
events.update((o)=>[{type: 'open', e}, ...o])
|
|
}
|
|
ws.onerror = (e) => {
|
|
events.update((o)=>[{type: 'error', e}, ...o])
|
|
}
|
|
ws.onclose = (e) => {
|
|
events.update((o)=>[{type: 'close', e}, ...o])
|
|
}
|
|
|
|
return {
|
|
send: (d) => { ws.send(JSON.stringify(d)) }, close: (code: number) => ws.close(code), ws
|
|
}
|
|
};
|