1 import LRUCache from 'lru-cache'
2 import { MOAuthTokenUser } from '@server/types/models'
3 import { LRU_CACHE } from '../../initializers/constants'
5 export class TokensCache {
7 private static instance: TokensCache
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 })
12 private constructor () { }
14 static get Instance () {
15 return this.instance || (this.instance = new this())
18 hasToken (token: string) {
19 return this.accessTokenCache.has(token)
22 getByToken (token: string) {
23 return this.accessTokenCache.get(token)
26 setToken (token: MOAuthTokenUser) {
27 this.accessTokenCache.set(token.accessToken, token)
28 this.userHavingToken.set(token.userId, token.accessToken)
31 deleteUserToken (userId: number) {
32 this.clearCacheByUserId(userId)
35 clearCacheByUserId (userId: number) {
36 const token = this.userHavingToken.get(userId)
38 if (token !== undefined) {
39 this.accessTokenCache.del(token)
40 this.userHavingToken.del(userId)
44 clearCacheByToken (token: string) {
45 const tokenModel = this.accessTokenCache.get(token)
47 if (tokenModel !== undefined) {
48 this.userHavingToken.del(tokenModel.userId)
49 this.accessTokenCache.del(token)