-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
81 lines (65 loc) · 1.75 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
const cast = require('./cast');
const shouldFetchFromEnv = ({
paramsLoaded,
paramsLoadedAt,
cache,
cacheExpiryInMillis,
}) => {
if (!cache || !paramsLoaded) {
return true;
}
const millisSinceLastLoad = new Date().getTime() - paramsLoadedAt.getTime();
if (cacheExpiryInMillis && millisSinceLastLoad > cacheExpiryInMillis) {
return true;
}
return false;
};
const getEnvVar = (key, type, fallback) => {
const value = process.env[key];
if (value !== undefined) {
return cast(value, type);
}
if (fallback) {
return fallback;
}
throw new ReferenceError(`Environment variable ${key} is missing`);
};
const getEnvVars = ({
names,
}) => Object.keys(names).reduce((env, key) => {
const config = names[key];
if (Array.isArray(config)) {
return Object.assign(env, {
[key]: getEnvVar(config[0], config[1], config[2]),
});
}
return Object.assign(env, {
[key]: getEnvVar(config),
});
}, {});
module.exports = (opts) => {
const defaults = {
setToContext: true,
names: {},
cache: false,
cacheExpiryInMillis: undefined,
paramsLoaded: false,
paramsCache: {},
paramsLoadedAt: new Date(0),
};
const options = Object.assign({}, defaults, opts);
return {
before: (handler, next) => {
const variables = shouldFetchFromEnv(options) ? getEnvVars(options) : options.paramsCache;
const targetParamsObject = options.setToContext ? handler.context : process.env;
Object.assign(targetParamsObject, variables);
options.paramsLoaded = true;
options.paramsCache = variables;
options.paramsLoadedAt = new Date();
// middy v2 removed the next function in favour of simply returning from the function
if (next) {
next();
}
},
};
};