ニジカ投稿局 https://tv.nizika.tv
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

53 lines
1.4 KiB

  1. import { LRUCache } from 'lru-cache'
  2. import { MOAuthTokenUser } from '@server/types/models/index.js'
  3. import { LRU_CACHE } from '../../initializers/constants.js'
  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.delete(token)
  29. this.userHavingToken.delete(userId)
  30. }
  31. }
  32. clearCacheByToken (token: string) {
  33. const tokenModel = this.accessTokenCache.get(token)
  34. if (tokenModel !== undefined) {
  35. this.userHavingToken.delete(tokenModel.userId)
  36. this.accessTokenCache.delete(token)
  37. }
  38. }
  39. }