ts/websocket.ts (raw)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
import util from "./util" import {AdapterState, AdapterData} from "./adapter"; import {Message, Attachment, Author} from "./message" var $ = util.$ var _ = util._ function connect() { var datastore: AdapterState = {} datastore = _("datastore", datastore); const wsProto = location.protocol == "https:" ? "wss" : "ws"; const _conn = new WebSocket(`${wsProto}://${location.host}/subscribe`, "underbbs"); _conn.addEventListener("open", (e: any) => { console.log("websocket connection opened"); console.log(JSON.stringify(e)); }); _conn.addEventListener("message", (e: any) => { // debugging console.log(e) // now we'll figure out what to do with it const data = JSON.parse(e.data); if (data.key) { _("skey", data.key) util.authorizedFetch("POST", "/api/adapters", JSON.stringify(_("settings").adapters)) } else { if (!datastore[data.adapter]) { datastore[data.adapter] = new AdapterData(data.protocol); } // typeswitch on the incoming data type and fill the memory switch (data.type) { case "message": datastore[data.adapter].messages.set(data.id, <Message>data); break; case "author": datastore[data.adapter].profileCache.set(data.id, <Author>data); break; default: break; } // if the adapter is active, inject the web components // FOR HOTFETCHED DATA: // before fetching, we can set properties on the DOM, // so when those data return to us we know where to inject components! if (_("currentAdapter") == data.adapter) { // dive in and insert that shit in the dom } } }); _conn.addEventListener("error", (e: any) => { console.log("websocket connection error"); console.log(JSON.stringify(e)); }); _("websocket", _conn); } export default { connect } |