This repository was archived by the owner on Mar 9, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconfig.js
84 lines (75 loc) · 2.05 KB
/
config.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
84
require('dotenv').config();
const env = process.env.NODE_ENV || dev;
// 'dev' or 'test' or 'prod'
const dev = {
name: 'dev',
app: {
port: process.env.PORT || 9000
},
db: {
name: 'todo-dev',
host: process.env.DB_HOST,
port: process.env.DB_PORT,
username: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD
}
};
const test = {
name: 'test',
app: {
port: process.env.PORT || 9000
},
db: {
name: 'todo-test',
host: process.env.DB_HOST,
port: process.env.DB_PORT,
username: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD
}
};
const prod = {
name: 'prod',
app: {
port: process.env.PORT || 9000
},
db: {
name: 'todo',
host: process.env.DB_HOST,
port: process.env.DB_PORT,
username: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD
}
};
const config = {
dev,
test,
prod
};
function _checkIfEnvIsValid(env) {
if (!env || !env.db || !env.db.host || !env.db.name) {
return false;
}
return true;
}
function getConnectionString(env) {
if (!_checkIfEnvIsValid(env)) {
throw "Passed invalid environment";
}
// for hosts without a port
// atlas clusters will not provide a port
// only localhost will have a port
// mongodb+srv://<username>:<password>@host/db-name
if (!env.db.port) {
if (env.db.username === '' || env.db.password === '') {
return `mongodb+srv://${env.db.host}/${env.db.name}`;
}
return `mongodb+srv://${env.db.username}:${env.db.password}@${env.db.host}/${env.db.name}`;
} else {
if (env.db.username === '' || env.db.password === '') {
return `mongodb+srv://${env.db.host}:${env.db.port}/${env.db.name}`;
}
return `mongodb+srv://${env.db.username}:${env.db.password}@${env.db.host}:${env.db.port}/${env.db.name}`;
}
}
module.exports = config[env] || config['dev'];
module.exports.dbConn = getConnectionString;