@andreabiagini5/applicazioni-e-servizi-web-project
Version:
Project for Applicazioni e Servizi Web.
54 lines • 1.95 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.connectDB = void 0;
const mongoose_1 = __importDefault(require("mongoose"));
const dotenv_1 = __importDefault(require("dotenv"));
const path_1 = __importDefault(require("path"));
/**
* Connects to MongoDB using Mongoose.
*/
const connectDB = async () => {
try {
let protocol;
let ip;
let port;
let dbName;
let username;
let password;
dotenv_1.default.config({ path: path_1.default.resolve(__dirname, '..', '..', '..', '..', '.env') });
protocol = 'mongodb';
ip = '172.0.0.12';
port = 27017;
dbName = process.env.DB_NAME;
username = process.env.DB_APP_USERNAME;
password = process.env.DB_APP_PASSWORD;
if (!username || !password || !dbName || !port || !ip || !protocol) {
let errorMsg = 'Missing MongoDB credentials. Please verify that the following variables are defined in the .env root file.';
for (const key of [
'DB_PROTOCOL',
'DB_APP_USERNAME',
'DB_APP_PASSWORD',
'DB_NAME',
'DB_PORT',
'DB_IP',
]) {
if (!process.env[key]) {
errorMsg += `\n- ${key}`;
}
}
throw new Error(errorMsg);
}
const uri = `${protocol}://${username}:${password}@${ip}:${port}/${dbName}`;
console.log('Connecting to MongoDB...', uri);
await mongoose_1.default.connect(uri);
console.log('MongoDB connected successfully');
}
catch (error) {
throw new DOMException('DB connection failed');
}
};
exports.connectDB = connectDB;
//# sourceMappingURL=db-connection.js.map