2023-05-22 11:04:39 -04:00
|
|
|
import { LRUCache } from 'lru-cache'
|
2023-07-31 08:34:36 -04:00
|
|
|
import { MOAuthTokenUser } from '@server/types/models/index.js'
|
|
|
|
import { LRU_CACHE } from '../../initializers/constants.js'
|
2021-03-12 09:20:46 -05:00
|
|
|
|
|
|
|
export class TokensCache {
|
|
|
|
|
|
|
|
private static instance: TokensCache
|
|
|
|
|
|
|
|
private readonly accessTokenCache = new LRUCache<string, MOAuthTokenUser>({ max: LRU_CACHE.USER_TOKENS.MAX_SIZE })
|
|
|
|
private readonly userHavingToken = new LRUCache<number, string>({ max: LRU_CACHE.USER_TOKENS.MAX_SIZE })
|
|
|
|
|
|
|
|
private constructor () { }
|
|
|
|
|
|
|
|
static get Instance () {
|
|
|
|
return this.instance || (this.instance = new this())
|
|
|
|
}
|
|
|
|
|
|
|
|
hasToken (token: string) {
|
|
|
|
return this.accessTokenCache.has(token)
|
|
|
|
}
|
|
|
|
|
|
|
|
getByToken (token: string) {
|
|
|
|
return this.accessTokenCache.get(token)
|
|
|
|
}
|
|
|
|
|
|
|
|
setToken (token: MOAuthTokenUser) {
|
|
|
|
this.accessTokenCache.set(token.accessToken, token)
|
|
|
|
this.userHavingToken.set(token.userId, token.accessToken)
|
|
|
|
}
|
|
|
|
|
|
|
|
deleteUserToken (userId: number) {
|
|
|
|
this.clearCacheByUserId(userId)
|
|
|
|
}
|
|
|
|
|
|
|
|
clearCacheByUserId (userId: number) {
|
|
|
|
const token = this.userHavingToken.get(userId)
|
|
|
|
|
|
|
|
if (token !== undefined) {
|
2022-12-29 08:18:07 -05:00
|
|
|
this.accessTokenCache.delete(token)
|
|
|
|
this.userHavingToken.delete(userId)
|
2021-03-12 09:20:46 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
clearCacheByToken (token: string) {
|
|
|
|
const tokenModel = this.accessTokenCache.get(token)
|
|
|
|
|
|
|
|
if (tokenModel !== undefined) {
|
2022-12-29 08:18:07 -05:00
|
|
|
this.userHavingToken.delete(tokenModel.userId)
|
|
|
|
this.accessTokenCache.delete(token)
|
2021-03-12 09:20:46 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|