MongoDB connection is now established once.

This commit is contained in:
Dorian Niemiec 2024-05-03 15:43:58 +02:00
parent c8b37a43ca
commit 0315e0222a

View file

@ -41,7 +41,6 @@ function generateUniqueShortenedURLID(db, callback) {
var id = generateShortenedURLID(); var id = generateShortenedURLID();
db.collection("urls").find({id: id}).toArray(function(err, result) { db.collection("urls").find({id: id}).toArray(function(err, result) {
if (err) { if (err) {
if(db.close) db.close();
callServerError(500, err); callServerError(500, err);
return; return;
} }
@ -58,6 +57,10 @@ function escapeRegExp(string) {
} }
function connectMongo(callback) { function connectMongo(callback) {
// customvar3 is a MongoDB database object
if (customvar3) {
callback(customvar3);
} else {
MongoClient.connect(mongoURL, function(err, db) { MongoClient.connect(mongoURL, function(err, db) {
if (err) { if (err) {
callServerError(500, err); callServerError(500, err);
@ -65,9 +68,11 @@ function connectMongo(callback) {
} }
var dbo = db.db(dbname); var dbo = db.db(dbname);
dbo.createCollection("urls", function(err, dbres) { dbo.createCollection("urls", function(err, dbres) {
customvar3 = dbo;
callback(dbo); callback(dbo);
}); });
}); });
}
} }
function formatTemplate(templateName, templateData, callback) { function formatTemplate(templateName, templateData, callback) {
@ -132,7 +137,6 @@ if (href.match(/^\/admin\/?$/)) {
connectMongo(function(db) { connectMongo(function(db) {
db.collection("urls").find({url: purl}).toArray(function(err, result) { db.collection("urls").find({url: purl}).toArray(function(err, result) {
if (err) { if (err) {
if(db.close) db.close();
callServerError(500, err); callServerError(500, err);
return; return;
} }
@ -142,7 +146,6 @@ if (href.match(/^\/admin\/?$/)) {
generateUniqueShortenedURLID(db, function(id) { generateUniqueShortenedURLID(db, function(id) {
db.collection("urls").insertOne({id: id, url: purl}, function(err, dbres) { db.collection("urls").insertOne({id: id, url: purl}, function(err, dbres) {
if (err) { if (err) {
if(db.close) db.close();
callServerError(500, err); callServerError(500, err);
return; return;
} }
@ -160,7 +163,6 @@ if (href.match(/^\/admin\/?$/)) {
connectMongo(function(db) { connectMongo(function(db) {
db.collection("urls").find({id: id}).toArray(function(err, result) { db.collection("urls").find({id: id}).toArray(function(err, result) {
if (err) { if (err) {
if(db.close) db.close();
callServerError(500, err); callServerError(500, err);
return; return;
} }