refactor: update to new room info protocol

This commit is contained in:
Shibo Lyu 2024-09-03 23:12:41 +08:00
parent 48f9c32918
commit f34ad89b79
2 changed files with 25 additions and 9 deletions

View file

@ -91,12 +91,17 @@ export class BlahChatServerConnection {
await this.apiCall('POST', `/room/${room}/item`, payload); await this.apiCall('POST', `/room/${room}/item`, payload);
} }
async fetchRoom( async fetchRoomInfo(roomId: string): Promise<BlahRoomInfo> {
roomId: string const room: BlahRoomInfo = await this.apiCall('GET', `/room/${roomId}`);
): Promise<{ room: BlahRoomInfo; messages: BlahSignedPayload<BlahMessage>[] }> { return room;
const [room, messages]: [BlahRoomInfo, [number, BlahSignedPayload<BlahMessage>][]] = }
await this.apiCall('GET', `/room/${roomId}/item`);
return { room, messages: messages.toSorted(([a], [b]) => a - b).map(([, message]) => message) }; async fetchRoomHistory(roomId: string): Promise<BlahSignedPayload<BlahMessage>[]> {
const { items }: { items: BlahSignedPayload<BlahMessage>[] } = await this.apiCall(
'GET',
`/room/${roomId}/item`
);
return items;
} }
private createEventSource(roomId: string): EventSource { private createEventSource(roomId: string): EventSource {

View file

@ -33,14 +33,25 @@
return server; return server;
} }
async function loadChat(server: BlahChatServerConnection) { async function loadChatInfo(server: BlahChatServerConnection) {
const { room, messages: blahMessages } = await server.fetchRoom(roomId); const room = await server.fetchRoomInfo(roomId);
chat = { chat = {
id: roomId, id: roomId,
name: room.title, name: room.title,
type: 'group' type: 'group'
}; };
messages = [...blahMessages.map(messageFromBlah), ...messages]; }
async function loadChatHistory(server: BlahChatServerConnection) {
const history = await server.fetchRoomHistory(roomId);
messages = [
...history.map(messageFromBlah).toSorted((a, b) => a.date.getTime() - b.date.getTime()),
...messages
];
}
async function loadChat(server: BlahChatServerConnection) {
return await Promise.allSettled([loadChatInfo(server), loadChatHistory(server)]);
} }
$: if (browser) initConnection($currentKeyPair).then((server) => loadChat(server)); $: if (browser) initConnection($currentKeyPair).then((server) => loadChat(server));