shorten wait time for grouping requests

This commit is contained in:
Wheat Carrier 2023-11-12 09:00:59 +08:00
parent 2a8fbb8b74
commit 4f82c9141f

View File

@ -23,13 +23,14 @@ class MessageBroker {
protected buffer: Array<{ protected buffer: Array<{
ids: number[]; ids: number[];
resolve: (result: unknown) => void; resolve: (result: unknown) => void;
reject: (error: unknown) => void;
}> = [], }> = [],
protected timeout: NodeJS.Timeout = null, protected timeout: NodeJS.Timeout = null,
) {} ) {}
async getMessagesByIds(ids: number[]) { async getMessagesByIds(ids: number[]) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
this.buffer.push({ ids, resolve }); this.buffer.push({ ids, resolve, reject });
if (this.timeout) { if (this.timeout) {
clearTimeout(this.timeout); clearTimeout(this.timeout);
} }
@ -37,18 +38,28 @@ class MessageBroker {
let buffer = []; let buffer = [];
[buffer, this.buffer] = [[...this.buffer], []]; [buffer, this.buffer] = [[...this.buffer], []];
const ids = [...new Set(buffer.map((item) => item.ids).flat())]; const ids = [...new Set(buffer.map((item) => item.ids).flat())];
const messages = await this.client.getMessages(this.privateChannelId, {
ids, try {
}); const messages = await this.client.getMessages(
const messageMap = new Map(); this.privateChannelId,
messages.forEach((message) => { {
messageMap.set(message.id, message); ids,
}); },
buffer.forEach((item) => { );
const result = item.ids.map((id: number) => messageMap.get(id)); const messageMap = new Map();
item.resolve(result); messages.forEach((message) => {
}); messageMap.set(message.id, message);
}, 500); });
buffer.forEach((item) => {
const result = item.ids.map((id: number) => messageMap.get(id));
item.resolve(result);
});
} catch (err) {
buffer.forEach((item) => {
item.reject(err);
});
}
}, 100);
}); });
} }
} }