generated from w4rlock/template-serverless-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
77 lines (64 loc) · 2.09 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
const { resolveAsyncConfigs } = require('config/async');
const _ = require('lodash');
class ServerlessConfig {
/**
* Default Constructor
*
* @param {object} serverless the serverless instance
*/
constructor(serverless) {
this.serverless = serverless;
// TODO
// region and stage can be overrided with --region some-region arguments.
// should be available to build the config object with node-config
const stage = serverless.getProvider('aws').getStage();
const region = serverless.getProvider('aws').getRegion();
process.env.NODE_ENV = stage;
process.env.AWS_REGION = region;
process.env.SLS_STAGE = stage;
// first set NODE_ENV after that import the config module
// eslint-disable-next-line global-require
this.config = require('config');
this.onceInit = _.once(async () => {
await resolveAsyncConfigs(this.config);
});
this.variableResolvers = {
config: {
serviceName: 'ServerlessConfig',
isDisabledAtPrepopulation: true,
resolver: this.dispatchAction.bind(this, this.getConfig),
},
};
}
/**
* Action Wrapper for common entry point
*
* @param {function} funAction serverless plugin action
*/
async dispatchAction(funAction, varResolver = undefined) {
await this.onceInit();
return funAction.call(this, varResolver);
}
/**
* Resolve serverless yml variable
*
* @param {string} prop custom string with default value support
* @returns {any} value for prop
*/
async getConfig(prop) {
let val = '';
const [, deepPath, defaultValue] = prop.split(':');
val = _.get(this.config, deepPath, defaultValue);
if (_.isEmpty(val) && !_.isBoolean(val)) {
let err = '';
err += 'KEY_OR_VALUE_IS_MISSING: ';
err += `key or value not found for '${deepPath}' key. `;
err += `Check in serverless.yml '${prop}' or configure this prop value.`;
err += 'https://github.com/lorenwest/node-config/wiki/';
err += 'Configuration-Files';
throw new Error(err);
}
return val;
}
}
module.exports = ServerlessConfig;