All files / src/utils tokenCache.ts

100% Statements 16/16
100% Branches 3/3
100% Functions 5/5
100% Lines 14/14

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33  7x     2x     2x       7x 7x   7x 7x 7x       9x 9x 9x   1x       16x 16x      
class TokenInfo {
  constructor(public accessToken: string, public expiresAt: Date) {}
}
 
export class TokenCache {
  private tokenMap: Map<string, TokenInfo>
  constructor() {
    this.tokenMap = new Map()
  }
 
  set({ scopes, clientId, expiresIn }: { scopes: string[]; clientId: string; expiresIn: number }, token: string) {
    const date = new Date()
    date.setSeconds(date.getSeconds() + expiresIn)
 
    const tokenInfo = new TokenInfo(token, date)
    const key = this._getTokenCacheKey({ scopes, clientId })
    this.tokenMap.set(key, tokenInfo)
  }
 
  get({ scopes, clientId }: { scopes: string[]; clientId: string }): string | undefined {
    const key = this._getTokenCacheKey({ scopes, clientId })
    const token = this.tokenMap.get(key)
    if (!token || token.expiresAt <= new Date()) return
 
    return token.accessToken
  }
 
  private _getTokenCacheKey({ scopes, clientId }: { scopes: string[]; clientId: string }) {
    const scopesKey = scopes.join('-')
    return `${scopesKey}:${clientId}`
  }
}