UNPKG

2.04 kBJavaScriptView Raw
1import { canPrefetch, createPrefetchClient, createClient, getCache, getInternal, processCache, modifyCache, jsonSafeParse } from '@middy/util';
2import SecretsManager from 'aws-sdk/clients/secretsmanager.js';
3const defaults = {
4 AwsClient: SecretsManager,
5 awsClientOptions: {},
6 awsClientAssumeRole: undefined,
7 awsClientCapture: undefined,
8 fetchData: {},
9 disablePrefetch: false,
10 cacheKey: 'secrets-manager',
11 cacheExpiry: -1,
12 setToContext: false
13};
14const secretsManagerMiddleware = (opts = {})=>{
15 const options = {
16 ...defaults,
17 ...opts
18 };
19 const fetch = (request, cachedValues = {})=>{
20 const values = {};
21 for (const internalKey of Object.keys(options.fetchData)){
22 if (cachedValues[internalKey]) continue;
23 values[internalKey] = client.getSecretValue({
24 SecretId: options.fetchData[internalKey]
25 }).promise().then((resp)=>jsonSafeParse(resp.SecretString)).catch((e)=>{
26 const value = getCache(options.cacheKey).value ?? {};
27 value[internalKey] = undefined;
28 modifyCache(options.cacheKey, value);
29 throw e;
30 });
31 }
32 return values;
33 };
34 let prefetch, client;
35 if (canPrefetch(options)) {
36 client = createPrefetchClient(options);
37 prefetch = processCache(options, fetch);
38 }
39 const secretsManagerMiddlewareBefore = async (request)=>{
40 if (!client) {
41 client = await createClient(options, request);
42 }
43 const { value } = prefetch ?? processCache(options, fetch, request);
44 Object.assign(request.internal, value);
45 if (options.setToContext) {
46 const data = await getInternal(Object.keys(options.fetchData), request);
47 Object.assign(request.context, data);
48 }
49 prefetch = null;
50 };
51 return {
52 before: secretsManagerMiddlewareBefore
53 };
54};
55export default secretsManagerMiddleware;
56
57
58//# sourceMappingURL=index.js.map
\No newline at end of file