-
Notifications
You must be signed in to change notification settings - Fork 167
/
entityCache.ts
79 lines (74 loc) · 2.36 KB
/
entityCache.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
// Which updates have the following fields?
import { getInputPeer, getPeerId } from "./Utils";
import { isArrayLike, returnBigInt } from "./Helpers";
import { Api } from "./tl";
import bigInt from "big-integer";
export class EntityCache {
private cacheMap: Map<string, any>;
constructor() {
this.cacheMap = new Map();
}
add(entities: any) {
const temp = [];
if (!isArrayLike(entities)) {
if (entities != undefined) {
if (typeof entities == "object") {
if ("chats" in entities) {
temp.push(...entities.chats);
}
if ("users" in entities) {
temp.push(...entities.users);
}
if ("user" in entities) {
temp.push(entities.user);
}
}
}
if (temp.length) {
entities = temp;
} else {
return;
}
}
for (const entity of entities) {
try {
const pid = getPeerId(entity);
if (!this.cacheMap.has(pid.toString())) {
this.cacheMap.set(pid.toString(), getInputPeer(entity));
}
} catch (e) {}
}
}
get(item: bigInt.BigInteger | string | undefined) {
if (item == undefined) {
throw new Error("No cached entity for the given key");
}
item = returnBigInt(item);
if (item.lesser(bigInt.zero)) {
let res;
try {
res = this.cacheMap.get(getPeerId(item).toString());
if (res) {
return res;
}
} catch (e) {
throw new Error("Invalid key will not have entity");
}
}
for (const cls of [Api.PeerUser, Api.PeerChat, Api.PeerChannel]) {
const result = this.cacheMap.get(
getPeerId(
new cls({
userId: item,
chatId: item,
channelId: item,
})
).toString()
);
if (result) {
return result;
}
}
throw new Error("No cached entity for the given key");
}
}