Skip to content

Instantly share code, notes, and snippets.

@romanbsd
Last active May 10, 2021 11:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save romanbsd/59fcc40f87642ea3b8201815c24f82bd to your computer and use it in GitHub Desktop.
Save romanbsd/59fcc40f87642ea3b8201815c24f82bd to your computer and use it in GitHub Desktop.
/* 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