-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
83 lines (76 loc) · 2.35 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
82
83
const request = require('request-promise');
const url = require('url');
const when = require('when');
const nodefn = require('when/node');
const dns = require('dns');
const logger = require('winston');
const mongoose = require('mongoose');
function resolveUri(opts) {
const key = opts.uri ? 'uri' : 'url';
var u = url.parse(opts[key]);
if(process.env.ENVIRONMENT_NAME) {
host = process.env.ENVIRONMENT_NAME+"."+host;
}
return nodefn
.call(dns.resolveSrv, u.hostname)
.then(function(srvs) {
return when
.map(srvs, function(srv) {
return nodefn
.call(dns.resolve, srv.name)
.then(function(a) {
return a + ':' + srv.port;
});
});
})
.then(function(hosts) {
return u.protocol + '//' + (u.auth ? u.auth + '@' : '') + hosts.join(',') + u.path
})
.then(function(host) {
opts[key] = host;
return opts;
});
}
function resolveRequest(opts) {
return resolveUri(opts)
.otherwise(function(){ return opts; } )
.then(function(opts) {
return when(request(opts));
});
}
function resolveMongoUri(uri) {
var orig_uri = uri;
return resolveUri({'uri': uri})
.then(function(host) {
return host.uri;
})
.otherwise(orig_uri);
}
function connectToMongo(uri) {
return resolveMongoUri(uri)
.then(function(uri) {
return mongoose.connect(uri, {useMongoClient: true, server: {reconnectTries: 10}});
})
.otherwise(function(err) {
logger.warn('Failed to connect to mongo on startup - retry in 10s: %s', err.stack, {});
mongoose.disconnect();
setTimeout(function () { return connectToMongo(uri).done(); }, 10000);
});
}
function connectToAgenda(uri,agenda){
return resolveMongoUri(uri)
.then(function(uri) {
agenda.agenda.agenda.database(uri, 'jobSchedule').maxConcurrency(100);
})
.otherwise(function(err) {
logger.warn('failed to connect to agenda on startup - retry in 10s: %s', err.stack, {});
setTimeout(function() { connectToAgenda(uri,agenda).done(); }, 10000);
});
}
if(process.env.OVERRIDE_DNS) {
console.log('using alternate nameserver:', process.env.OVERRIDE_DNS);
dns.setServers([process.env.OVERRIDE_DNS]);
}
module.exports.connectToAgenda = connectToAgenda;
module.exports.connectToMongo = connectToMongo;
module.exports.resolveRequest = resolveRequest;