Created
October 20, 2021 17:04
-
-
Save zhuangdaz/68979605ab4e908a71f51051b89d6e61 to your computer and use it in GitHub Desktop.
SSM utils for fetching and caching parameters
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
import { SSM } from "aws-sdk"; | |
import ms from "ms"; | |
const ssm = new SSM(); | |
const SSM_PATH = process.env.SSM_PATH; | |
let cache = { params: {} }; | |
const getParametersByPath = async (path) => | |
ssm | |
.getParametersByPath({ | |
Path: path, | |
Recursive: true, | |
}) | |
.promise(); | |
const loadParameters = async (cacheDuration = "1h") => { | |
if (!isCacheEmpty() && !hasCacheExpired()) { | |
// cache is valid. Do not reload. | |
return; | |
} | |
console.log("Reloading SSM param cache..."); | |
if (SSM_PATH === null || SSM_PATH.length === 0) { | |
throw new Error( | |
"SSM_PATH is null. Please provide it via environment variables" | |
); | |
} | |
const response = await getParametersByPath(SSM_PATH); | |
const params = response.Parameters.reduce( | |
(result, param) => ({ | |
...result, | |
[param.Name.substring(SSM_PATH.length + 1)]: param.Value, | |
}), | |
{} | |
); | |
//Update cache with new data and expiry | |
cache = { params, expiredAt: new Date(Date.now() + ms(cacheDuration)) }; | |
}; | |
function isCacheEmpty() { | |
return Object.keys(cache.params).length === 0; | |
} | |
function hasCacheExpired() { | |
return !cache.expiredAt || new Date() > cache.expiredAt; | |
} | |
export const getParameters = async () => { | |
await loadParameters(); | |
return cache.params; | |
}; | |
export const getRootSSMPath = (scope) => { | |
if (scope && scope.name && scope.stage) { | |
return `/${scope.stage}/${scope.name}`; | |
} else { | |
return null; | |
} | |
}; | |
export const createSSMPath = (scope, key) => { | |
if (scope && scope.name && scope.stage) { | |
return `${getRootSSMPath(scope)}/${key}`; | |
} else { | |
return null; | |
} | |
}; | |
export const SSM_KEYS = { | |
USER_POOL_ID: "USER_POOL_ID", | |
USER_POOL_CLIENT_ID: "USER_POOL_CLIENT_ID", | |
MEETINGS_TABLE: "MEETINGS_TABLE", | |
USERS_TABLE: "USERS_TABLE", | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment