Newer
Older
import EventEmitter from "eventemitter3";
ClientConfig,
ClientToServerEvents,
ServerToClientEvents,
export interface INetworkEvents {
user: (user: AuthSession) => void;
config: (user: ClientConfig) => void;
canvas: (pixels: string[]) => void;
pixels: (data: { available: number }) => void;
pixelLastPlaced: (time: number) => void;
}
type SentEventValue<K extends keyof INetworkEvents> = EventEmitter.ArgumentMap<
Exclude<INetworkEvents, string | symbol>
>[Extract<K, keyof INetworkEvents>];
class Network extends EventEmitter<INetworkEvents> {
socket: Socket<ServerToClientEvents, ClientToServerEvents> = io(
import.meta.env.VITE_API_HOST,
{
autoConnect: false,
private online_count = 0;
private sentEvents: {
[key in keyof INetworkEvents]?: SentEventValue<key>;
} = {};
constructor() {
super();
this.socket.on("user", (user: AuthSession) => {
this.emit("user", user);
});
this.socket.on("config", (config) => {
this.emit("config", config);
});
this.socket.on("canvas", (pixels) => {
this._emit("canvas", pixels);
});
this.socket.on("availablePixels", (count) => {
this._emit("pixels", { available: count });
});
this.socket.on("pixelLastPlaced", (time) => {
this._emit("pixelLastPlaced", time);
});
this.socket.on("online", ({ count }) => {
this._emit("online", count);
});
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
// this.socket.on("config", (config) => {
// Pallete.load(config.pallete);
// Canvas.load(config.canvas);
// });
// this.socket.on("pixel", (data: SPixelPacket) => {
// Canvas.handlePixel(data);
// });
// this.socket.on("canvas", (data: SCanvasPacket) => {
// Canvas.handleBatch(data);
// });
}
private _emit: typeof this.emit = (event, ...args) => {
this.sentEvents[event] = args;
return this.emit(event, ...args);
};
waitFor<Ev extends keyof INetworkEvents & (string | symbol)>(
ev: Ev
): Promise<SentEventValue<Ev>> {
return new Promise((res) => {
if (this.sentEvents[ev]) return res(this.sentEvents[ev]!);
this.once(ev, (...data) => {
res(data);
});
});
}
/**
* Get online user count
* @returns online users count
*/
getOnline() {
return this.online_count;
}
}
export default new Network() as Network;