-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.ts
31 lines (30 loc) · 1.13 KB
/
config.ts
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
/**
* In this file we load the Environment Variables and configure the database connection
*/
import mongoose from 'mongoose';
export const PORT = process.env.PORT || 3000;
export const DB_HOST = process.env.DB_HOST || "localhost";
export const DB_PORT = process.env.DB_PORT || 27017;
export const DB_NAME = process.env.DB_NAME || "brazilian-addon-db";
const DB_USER = process.env.DB_USER;
const DB_PSK = process.env.DB_PSK;
/**
* Connect to a database through an URI built with the available Environment Variables
* @returns URI to the database
*/
export async function connect() : Promise<string> {
let CREDENTIALS = "";
if (DB_USER && DB_PSK) CREDENTIALS = `${DB_USER}:${DB_PSK}@`;
let mongouri = `mongodb+srv://${CREDENTIALS}${DB_HOST}:/${DB_NAME}`;
try {
await mongoose.connect(mongouri);
} catch (err) {
mongouri = `mongodb://${CREDENTIALS}${DB_HOST}:${DB_PORT}/${DB_NAME}`;
try {
await mongoose.connect(mongouri);
} catch (err) {
throw new Error(`Could not connect to db 'mongodb://${DB_HOST}:${DB_PORT}/${DB_NAME}': ${err}`);
}
}
return mongouri;
}