]>
Commit | Line | Data |
---|---|---|
41fb13c3 | 1 | import LRUCache from 'lru-cache' |
f43db2f4 C |
2 | import { MOAuthTokenUser } from '@server/types/models' |
3 | import { LRU_CACHE } from '../../initializers/constants' | |
4 | ||
5 | export class TokensCache { | |
6 | ||
7 | private static instance: TokensCache | |
8 | ||
9 | private readonly accessTokenCache = new LRUCache<string, MOAuthTokenUser>({ max: LRU_CACHE.USER_TOKENS.MAX_SIZE }) | |
10 | private readonly userHavingToken = new LRUCache<number, string>({ max: LRU_CACHE.USER_TOKENS.MAX_SIZE }) | |
11 | ||
12 | private constructor () { } | |
13 | ||
14 | static get Instance () { | |
15 | return this.instance || (this.instance = new this()) | |
16 | } | |
17 | ||
18 | hasToken (token: string) { | |
19 | return this.accessTokenCache.has(token) | |
20 | } | |
21 | ||
22 | getByToken (token: string) { | |
23 | return this.accessTokenCache.get(token) | |
24 | } | |
25 | ||
26 | setToken (token: MOAuthTokenUser) { | |
27 | this.accessTokenCache.set(token.accessToken, token) | |
28 | this.userHavingToken.set(token.userId, token.accessToken) | |
29 | } | |
30 | ||
31 | deleteUserToken (userId: number) { | |
32 | this.clearCacheByUserId(userId) | |
33 | } | |
34 | ||
35 | clearCacheByUserId (userId: number) { | |
36 | const token = this.userHavingToken.get(userId) | |
37 | ||
38 | if (token !== undefined) { | |
39 | this.accessTokenCache.del(token) | |
40 | this.userHavingToken.del(userId) | |
41 | } | |
42 | } | |
43 | ||
44 | clearCacheByToken (token: string) { | |
45 | const tokenModel = this.accessTokenCache.get(token) | |
46 | ||
47 | if (tokenModel !== undefined) { | |
48 | this.userHavingToken.del(tokenModel.userId) | |
49 | this.accessTokenCache.del(token) | |
50 | } | |
51 | } | |
52 | } |