Files
Veskslop-t/poc/public/api.js
T

66 lines
1.6 KiB
JavaScript

"use strict";
window.VK = window.VK ?? {};
const bus = new Map();
window.VK.bus = {
on(type, handler) {
const handlers = bus.get(type) ?? new Set();
handlers.add(handler);
bus.set(type, handlers);
return () => handlers.delete(handler);
},
emit(type, payload) {
for (const handler of bus.get(type) ?? []) {
try {
handler(payload);
} catch (error) {
console.error(`[bus] ${type} handler failed`, error);
}
}
}
};
async function request(path, options) {
const response = await fetch(path, options);
let body;
try {
body = await response.json();
} catch {
throw new Error(`request failed (${response.status})`);
}
if (!body.ok) {
const error = new Error(body.error ?? `request failed (${response.status})`);
if (body.code) error.code = body.code;
throw error;
}
return body.result;
}
window.VK.api = {
get: path => request(path),
post: (path, data) =>
request(path, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data ?? {})
})
};
window.VK.connectEvents = function connectEvents() {
const source = new EventSource("/api/events");
source.onmessage = message => {
let data;
try {
data = JSON.parse(message.data);
} catch {
return;
}
window.VK.bus.emit("event", data);
};
source.onerror = () => window.VK.bus.emit("sse-error");
};