summaryrefslogtreecommitdiff
path: root/hi-ui/src/apiServer.js
diff options
context:
space:
mode:
Diffstat (limited to 'hi-ui/src/apiServer.js')
-rw-r--r--hi-ui/src/apiServer.js102
1 files changed, 102 insertions, 0 deletions
diff --git a/hi-ui/src/apiServer.js b/hi-ui/src/apiServer.js
new file mode 100644
index 0000000..5e521de
--- /dev/null
+++ b/hi-ui/src/apiServer.js
@@ -0,0 +1,102 @@
+import axios from 'axios';
+import { activeChannel, channelsList, events } from './store';
+
+export const apiServer = axios.create({
+ baseURL: '/api/',
+});
+
+export async function boot() {
+ return apiServer.get('/boot');
+}
+
+export async function logIn(username, password) {
+ const data = {
+ name: username,
+ password,
+ };
+ return apiServer.post('/auth/login', data);
+}
+
+export async function logOut() {
+ return apiServer.post('/auth/logout', {});
+}
+
+export async function listChannels() {
+ return apiServer.get('/channels');
+}
+
+export async function createChannel(name) {
+ return apiServer.post('/channels', { name });
+}
+
+export async function postToChannel(channelId, message) {
+ return apiServer.post(`/channels/${channelId}`, { message });
+}
+
+export async function deleteMessage(messageId) {
+ // TODO
+}
+
+export function subscribeToEvents() {
+ const evtSource = new EventSource("/api/events");
+ events.update(() => []);
+ // TODO: this should process all incoming events and store them.
+ // TODO: eventually we'll need to handle expiring old info, so as not to use
+ // infinite browser memory.
+ /*
+ * Known message types as of now:
+ * - created: a channel is created.
+ * - action: ignore.
+ * - message: a message is created.
+ * - action: display message in channel.
+ * - message_deleted: a message is deleted.
+ * - action: replace message with <...>.
+ * - deleted: a channel is deleted.
+ * - action: remove channel from sidebar.
+ */
+ evtSource.onmessage = (evt) => {
+ const data = JSON.parse(evt.data);
+
+ switch (data.type) {
+ case 'created':
+ break;
+ case 'message':
+ events.update((value) => {
+ const eventList = [...value, data];
+ eventList.sort((a, b) => a.at - b.at);
+ return eventList;
+ });
+ break;
+ case 'message_deleted':
+ events.update((value) => {
+ const eventList = value.map((el) => {
+ if (el.message?.id === data.message) {
+ el.message.body = '&laquo;&hellip;&raquo;';
+ return el
+ } else {
+ return el;
+ }
+ });
+ return eventList;
+ });
+ break;
+ case 'deleted':
+ activeChannel.update((value) => {
+ if (value?.id === data.channel) {
+ return null;
+ }
+ return value;
+ });
+ channelsList.update((value) => {
+ const channelIndex = value.map((e) => e.id).indexOf(data.channel);
+ if (channelIndex !== -1) {
+ value.splice(channelIndex, 1);
+ }
+ return value;
+ });
+ break;
+ default:
+ break;
+ }
+ }
+}