2021-04-16 11:32:00 +10:00
|
|
|
class EventEmitter<T> {
|
|
|
|
public callbacks: { [key: string]: Array<(data: T) => void> };
|
|
|
|
|
|
|
|
constructor() {
|
|
|
|
this.callbacks = {};
|
|
|
|
}
|
|
|
|
|
|
|
|
on(event: string, cb: (data: T) => void) {
|
|
|
|
if (!this.callbacks[event]) this.callbacks[event] = [];
|
|
|
|
this.callbacks[event].push(cb);
|
|
|
|
}
|
|
|
|
|
|
|
|
emit(event: string, data: T) {
|
|
|
|
let cbs = this.callbacks[event];
|
|
|
|
if (cbs) {
|
2021-04-19 12:55:33 +10:00
|
|
|
cbs.forEach((cb) => cb(data));
|
2021-04-16 11:32:00 +10:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export interface Message {
|
|
|
|
timestamp: Date;
|
|
|
|
handle: string;
|
|
|
|
message: string;
|
|
|
|
}
|
|
|
|
|
|
|
|
export default class WakuMock extends EventEmitter<Message> {
|
|
|
|
index: number;
|
|
|
|
intervalId?: number | NodeJS.Timeout;
|
|
|
|
|
|
|
|
private constructor() {
|
|
|
|
super();
|
|
|
|
this.index = 0;
|
|
|
|
}
|
|
|
|
|
|
|
|
public static async create(): Promise<WakuMock> {
|
2021-04-19 10:36:37 +10:00
|
|
|
await new Promise((resolve) => setTimeout(resolve, 500));
|
2021-04-16 11:32:00 +10:00
|
|
|
|
|
|
|
const wakuMock = new WakuMock();
|
|
|
|
wakuMock.startInterval();
|
|
|
|
return wakuMock;
|
|
|
|
}
|
|
|
|
|
|
|
|
public async send(message: string): Promise<void> {
|
|
|
|
const timestamp = new Date();
|
2022-02-04 14:12:00 +11:00
|
|
|
const handle = "me";
|
|
|
|
this.emit("message", {
|
2021-04-16 11:32:00 +10:00
|
|
|
timestamp,
|
|
|
|
handle,
|
2021-04-19 12:55:33 +10:00
|
|
|
message,
|
2021-04-16 11:32:00 +10:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
private startInterval() {
|
|
|
|
if (this.intervalId === undefined) {
|
|
|
|
this.intervalId = setInterval(this.emitMessage.bind(this), 1000);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
private emitMessage() {
|
2022-02-04 14:12:00 +11:00
|
|
|
const handle = "you";
|
2021-04-16 11:32:00 +10:00
|
|
|
const timestamp = new Date();
|
2022-02-04 14:12:00 +11:00
|
|
|
this.emit("message", {
|
2021-04-16 11:32:00 +10:00
|
|
|
timestamp,
|
|
|
|
handle,
|
2021-04-19 12:55:33 +10:00
|
|
|
message: `This is message #${this.index++}.`,
|
2021-04-16 11:32:00 +10:00
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|