Skip to content

Instantly share code, notes, and snippets.

@kylegalbraith
Created September 10, 2017 18:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kylegalbraith/a35f136a17d83b5689c5e2a38392f3ae to your computer and use it in GitHub Desktop.
Save kylegalbraith/a35f136a17d83b5689c5e2a38392f3ae to your computer and use it in GitHub Desktop.
var mongodb = require('mongodb'),
MongoClient = mongodb.MongoClient,
dbUrl = process.env.MONGOLAB_URI,
urlObj = {},
urlInserted = false,
ids;
function generateRandomId(currIds) {
var randomId = Math.floor(Math.random() * 10000);
if (currIds.indexOf(randomId) < 0) {
return randomId;
} else {
generateRandomId(currIds);
}
}
function getMongoData() {
return new Promise(function(resolve, reject) {
MongoClient.connect(dbUrl, function(err, db) {
if (err) {
console.log('Unable to connect to the mongoDB server. Error:', err);
reject(err);
} else {
console.log('Connection established to', dbUrl);
reject(err);
}
// Start db work.
var collection = db.collection('urls'),
shortId;
collection.distinct("_id").then(function(data) {
shortId = generateRandomId(data)})
.then(function() {
urlObj = {
"original_url": originalUrl,
"short_url": baseUrl + shortId
}
collection.insert({
"_id": shortId,
"original_url": originalUrl,
"short_url": baseUrl + shortId
}, {w: 1}, function() {
// urlInserted = true;
db.close();
// resolve(urlObj);
});
if (Object.keys(urlObj).length > 0) {
resolve(urlObj);
}
});
// db.close();
}); // End MongoDB connection
});
}
module.exports = function(originalUrl, baseUrl) {
return new Promise(function(resolve, reject) {
getMongoData().then(function(data) {
resolve(data);
}).catch(function(err) {
reject(err);
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment