UNPKG

@middy/secrets-manager

Version:

Secrets Manager middleware for the middy framework

58 lines (56 loc) 2.04 kB
import { canPrefetch, createPrefetchClient, createClient, getCache, getInternal, processCache, modifyCache, jsonSafeParse } from '@middy/util'; import SecretsManager from 'aws-sdk/clients/secretsmanager.js'; const defaults = { AwsClient: SecretsManager, awsClientOptions: {}, awsClientAssumeRole: undefined, awsClientCapture: undefined, fetchData: {}, disablePrefetch: false, cacheKey: 'secrets-manager', cacheExpiry: -1, setToContext: false }; const secretsManagerMiddleware = (opts = {})=>{ const options = { ...defaults, ...opts }; const fetch = (request, cachedValues = {})=>{ const values = {}; for (const internalKey of Object.keys(options.fetchData)){ if (cachedValues[internalKey]) continue; values[internalKey] = client.getSecretValue({ SecretId: options.fetchData[internalKey] }).promise().then((resp)=>jsonSafeParse(resp.SecretString)).catch((e)=>{ const value = getCache(options.cacheKey).value ?? {}; value[internalKey] = undefined; modifyCache(options.cacheKey, value); throw e; }); } return values; }; let prefetch, client; if (canPrefetch(options)) { client = createPrefetchClient(options); prefetch = processCache(options, fetch); } const secretsManagerMiddlewareBefore = async (request)=>{ if (!client) { client = await createClient(options, request); } const { value } = prefetch ?? processCache(options, fetch, request); Object.assign(request.internal, value); if (options.setToContext) { const data = await getInternal(Object.keys(options.fetchData), request); Object.assign(request.context, data); } prefetch = null; }; return { before: secretsManagerMiddlewareBefore }; }; export default secretsManagerMiddleware; //# sourceMappingURL=index.js.map