-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
79 lines (65 loc) · 2.56 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
var httpClient = require('http');
var url = require('url');
function createPropertySources(properties){
return {
get(key){
for(var prop of properties.propertySources){
var value = prop.source[key];
if(value !== undefined)
return value;
}
}
};
}
function buildURL(location){
location = process.env['NODE_CONFIG_CLIENT_LOCATION'] ? process.env['NODE_CONFIG_CLIENT_LOCATION'] : location;
return url.parse('http://'+location);
}
function buildAuth(user){
user.name = process.env['NODE_CONFIG_CLIENT_USER_NAME'] ? process.env['NODE_CONFIG_CLIENT_USER_NAME'] : user.name;
user.password = process.env['NODE_CONFIG_CLIENT_USER_PASSWORD'] ? process.env['NODE_CONFIG_CLIENT_USER_PASSWORD'] : user.password;
return user.name+':'+user.password;
}
function validateConfig(config){
if(process.env['NODE_CONFIG_CLIENT_NAME'] && !config.name)
throw new Error('Name field not defined');
if(!process.env['NODE_CONFIG_CLIENT_PROFILES'] && (!config.profiles || !config.profiles.length))
config.profiles = ['default'];
if(!process.env['NODE_CONFIG_CLIENT_LOCATION'] && !config.location)
throw new Error('Location field not set');
}
function buildPath(applicationName,profiles,label){
applicationName = process.env['NODE_CONFIG_CLIENT_NAME'] ? process.env['NODE_CONFIG_CLIENT_NAME'] : applicationName
profiles = process.env['NODE_CONFIG_CLIENT_PROFILES'] ? process.env['NODE_CONFIG_CLIENT_PROFILES'] : profiles.join();
return '/'+applicationName+'/'+profiles+(label ? '/'+label : '');
}
function requestConfig(config){
return new Promise(function(resolve,reject){
var body = null;
httpClient.get({
host:buildURL(config.location).hostname,
port:buildURL(config.location).port,
path:buildPath(config.name,config.profiles,config.label),
auth:config.user ? buildAuth(config.user) : ""
},function(res){
res.on('error',function(e){
reject(e);
});
res.on('data',function(data){
body = JSON.parse(data);
});
res.on('end',function(e){
resolve(body);
});
}).on('error',function(e){
reject(e);
}).end();
});
}
exports.load = function(config){
validateConfig(config);
return requestConfig(config)
.then(function(configurations){
return createPropertySources(configurations);
});
}