Add support for backlog

This commit is contained in:
Hamcha 2019-06-11 11:58:16 +02:00
parent d0ecfde2b0
commit 4a1d6c6f1c
Signed by: hamcha
GPG key ID: A40413D21021EAEE
2 changed files with 18 additions and 4 deletions

View file

@ -10,6 +10,7 @@ export type MessageHandler = (msg: RoomServerMessage) => void;
export default class RoomClient { export default class RoomClient {
private ws: WebSocket; private ws: WebSocket;
public info: Room; public info: Room;
public backlog: RoomServerMessage[];
private onMessage?: MessageHandler; private onMessage?: MessageHandler;
private buffer: RoomServerMessage[]; private buffer: RoomServerMessage[];
@ -17,6 +18,7 @@ export default class RoomClient {
constructor(_ws: WebSocket, _info: Room) { constructor(_ws: WebSocket, _info: Room) {
this.info = _info; this.info = _info;
this.buffer = []; this.buffer = [];
this.backlog = [];
this.ws = _ws; this.ws = _ws;
this.ws.addEventListener("message", this._received.bind(this)); this.ws.addEventListener("message", this._received.bind(this));
} }
@ -48,12 +50,20 @@ export default class RoomClient {
// Unregister handler // Unregister handler
ws.removeEventListener("message", onMessage); ws.removeEventListener("message", onMessage);
// Parse message // Parse message
let data = JSON.parse(ev.data); let data = JSON.parse(ev.data) as RoomServerMessage;
if ("error" in data) { if ("error" in data) {
reject(data.error); reject(data.error);
} }
let client = new RoomClient(ws, data.event.room); if (data.room) {
resolve(client); let client = new RoomClient(ws, data.room);
// Check for backlog
if (data.backlog) {
client.backlog = data.backlog;
}
resolve(client);
} else {
reject("missing room info");
}
}; };
ws.addEventListener("message", onMessage); ws.addEventListener("message", onMessage);
ws.addEventListener("open", ev => { ws.addEventListener("open", ev => {

View file

@ -36,9 +36,12 @@ export interface RoomMessage {
export interface RoomServerMessage { export interface RoomServerMessage {
time: "string"; time: "string";
type: "event" | "message"; type: "event" | "message" | "welcome";
event?: RoomEvent; event?: RoomEvent;
message?: RoomMessage; message?: RoomMessage;
error?: string;
backlog?: RoomServerMessage[];
room?: Room;
} }
export interface RoomState { export interface RoomState {
@ -60,6 +63,7 @@ const mutations: MutationTree<RoomState> = {
state.client = ws; state.client = ws;
state.in_room = true; state.in_room = true;
state.room = ws.info; state.room = ws.info;
state.messages = ws.backlog;
}, },
messageReceived(state: RoomState, msg: RoomServerMessage) { messageReceived(state: RoomState, msg: RoomServerMessage) {
state.messages.push(msg); state.messages.push(msg);