underbbs/frontend/ts/websocket.ts

54 lines
No EOL
1.7 KiB
TypeScript

import util from "./util"
import {AdapterState, AdapterData} from "./adapter";
import {Message, Attachment, Author} from "./message"
var $ = util.$
var _ = util._
function connect() {
let datastore = <AdapterState>_("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) => {
const data = JSON.parse(e.data);
console.log(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 signal it that there's new data
let adapter = $(`adapter_${data.adapter}`);
if (adapter) {
adapter.setAttribute("data-latest", data.id);
}
}
});
_conn.addEventListener("error", (e: any) => {
console.log("websocket connection error");
console.log(JSON.stringify(e));
});
_("websocket", _conn);
}
export default { connect }