tokens-cache.ts 1.4 KB

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