import { CACHE_MANAGER , HttpService , Inject , Injectable } from '@nestjs/common' ; import { ConfigService } from '@nestjs/config' ; import { Cache } from 'cache-manager' ; import { TokenResponse } from './interfaces/token.interface' ; @ Injectable ( ) export class TokenCacheService { private url = `${ this . config . get ( 'API_URL' ) }/auth/token` ; constructor ( private readonly http , private readonly config , @ Inject ( CACHE_MANAGER ) private cacheManager ) { } public async getNewToken ( serverId , scopes ) { const response = await this . http . post ( this . url , { scopes : scopes , serverId , } , { headers : { 'Client-Token' : this . config . get ( 'API_TOKEN' ) } } ) . toPromise ( ) ; const payload = response . data as TokenResponse ; return payload ; } private async cacheToken ( token ) { const cacheKey = this . prepareCacheKey ( token . keyspace ) ; await this . cacheManager . set ( cacheKey , token . accessToken , { ttl : token . expiresIn , } ) ; } private prepareCacheKey ( serverId ) { return `token-${ serverId }` ; } public async returnToken ( serverId ) { const cacheKey = this . prepareCacheKey ( serverId ) ; let accessToken = await this . cacheManager . get ( cacheKey ) ; try { if ( ! accessToken ) { throw new Error ( "AccessToken couldn't be retrieved from Cache" ) ; } } catch ( e ) { const response = await this . getNewToken ( serverId , [ 'Data.Read' , 'Data.Write' , ] ) ; await this . cacheToken ( response ) ; accessToken = response . accessToken ; } return accessToken ; } }