Last active
May 10, 2021 11:33
-
-
Save romanbsd/59fcc40f87642ea3b8201815c24f82bd to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* eslint-disable @typescript-eslint/no-explicit-any */ | |
import { AppConfig } from 'aws-sdk' | |
import { hostname } from 'os' | |
const TTL = 30 * 1000 // ms | |
export default class CachedAppConfig { | |
cache: any = {} | |
client: AppConfig | |
version: AppConfig.Version = 'null' | |
refreshTime = 0 | |
constructor(private app: string, private env: string, private profile: string, private clientId = hostname()) { | |
this.client = new AppConfig({ region: 'us-east-1' }) | |
} | |
getConfiguration(): Promise<any> { | |
if (this.isRefreshNeeded) { | |
const params = { | |
Application: this.app, | |
ClientId: this.clientId, | |
Configuration: this.profile, | |
Environment: this.env, | |
ClientConfigurationVersion: this.version | |
} | |
return this.client.getConfiguration(params).promise().then(config => { | |
if (config.ContentType === 'application/json') { | |
const content = config.Content.toString() | |
if (content) { | |
this.cache = JSON.parse(content) | |
} | |
} else { | |
throw new Error('Only JSON configuration is supported') | |
} | |
this.version = config.ConfigurationVersion | |
this.refreshTime = this.currentTimeMillis + TTL | |
return this.cache | |
}) | |
} else { | |
return Promise.resolve(this.cache) | |
} | |
} | |
private get isRefreshNeeded(): boolean { | |
return this.currentTimeMillis >= this.refreshTime | |
} | |
private get currentTimeMillis(): number { | |
return new Date().getTime() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment