summaryrefslogtreecommitdiff
path: root/hi-ui/src/apiServer.js
blob: f4a89a4b6504622546b68b8128bbeb1c28a8ce4f (plain)
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import axios from 'axios';
import { activeChannel, channelsList, messages } 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 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(resume_point) {
  const eventsUrl = new URL('/api/events', window.location);
  eventsUrl.searchParams.append('resume_point', resume_point);
  const evtSource = new EventSource(eventsUrl.toString());
  // 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':
        channelsList.update((value) => value.addChannel(data.channel))
        break;
      case 'message':
        messages.update((value) => value.addMessage(data));
        break;
      case 'message_deleted':
        messages.update((value) => value.deleteMessage(data.channel.id, data.message));
        break;
      case 'deleted':
        activeChannel.update((value) => value.deleteChannel(data.channel));
        channelsList.update((value) => value.deleteChannel(data.channel));
        messages.update((value) => value.deleteChannel(data.channel));
        break;
      default:
        break;
    }
  }
}