entityCache.ts 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // Which updates have the following fields?
  2. import {getInputPeer, getPeerId, } from "./Utils";
  3. import {isArrayLike} from './Helpers'
  4. import {Api} from "./tl";
  5. export class EntityCache {
  6. private cacheMap: Map<number, any>;
  7. constructor() {
  8. this.cacheMap = new Map();
  9. }
  10. add(entities: any) {
  11. const temp = [];
  12. if (!isArrayLike(entities)) {
  13. if (entities != undefined){
  14. if (typeof entities == 'object'){
  15. if ('chats' in entities) {
  16. temp.push(...entities.chats)
  17. }
  18. if ('users' in entities) {
  19. temp.push(...entities.users)
  20. }
  21. if ('user' in entities) {
  22. temp.push(entities.user)
  23. }
  24. }
  25. }
  26. if (temp.length) {
  27. entities = temp;
  28. } else {
  29. return;
  30. }
  31. }
  32. for (const entity of entities) {
  33. try {
  34. const pid = getPeerId(entity);
  35. if (!this.cacheMap.has(pid)) {
  36. this.cacheMap.set(pid, getInputPeer(entity));
  37. }
  38. } catch (e) {
  39. }
  40. }
  41. }
  42. get(item: any) {
  43. if (!(typeof item === 'number') || item < 0) {
  44. let res;
  45. try {
  46. res = this.cacheMap.get(getPeerId(item));
  47. if (res) {
  48. return res;
  49. }
  50. } catch (e) {
  51. throw new Error('Invalid key will not have entity')
  52. }
  53. }
  54. for (const cls of [Api.PeerUser, Api.PeerChat, Api.PeerChannel]) {
  55. // TODO remove these "as"
  56. const result = this.cacheMap.get(getPeerId(new cls({
  57. userId: item as number,
  58. chatId: item as number,
  59. channelId: item as number
  60. })));
  61. if (result) {
  62. return result;
  63. }
  64. }
  65. throw new Error('No cached entity for the given key');
  66. }
  67. }