diff --git a/package.json b/package.json index 47e2c5d..dcc367f 100644 --- a/package.json +++ b/package.json @@ -8,7 +8,7 @@ "node": ">= v0.4.12 < 0.7.0" }, "dependencies": { - "express":"2.5.4", - "short":"1.3" + "express": "4.4.1", + "short": "2.2" } } \ No newline at end of file diff --git a/short.js b/short.js index 1189262..77937d4 100644 --- a/short.js +++ b/short.js @@ -1,11 +1,15 @@ var url = require('url'), express = require('express'), short = require('short'), - app = express.createServer(), + app = express(), port = process.env.PORT || 8080, - domain = "http://192.168.1.111"; + domain = process.env.DOMAIN || ("http://localhost:" + port); + mongo = process.env.MONGODB || "mongodb://localhost/short"; -short.connect("mongodb://localhost/short"); +short.connect(mongo); +short.connection.on('error', function(error) { + throw new Error(error); +}); app.get('/api/*', function (req, res) { if (req.url === '/favicon.ico') { @@ -14,15 +18,13 @@ app.get('/api/*', function (req, res) { var removeApi = req.url.slice(5), URL = removeApi, options = {length: 7}; - short.generate(URL, options, function (error, shortURL) { - if (error) { - console.error(error); - } - else { - var tinyUrl = [domain, ":", port, "/", shortURL.hash].join(""); - console.log(["URL is ", shortURL.URL, " ", tinyUrl].join("")); - res.end(tinyUrl); - } + short.generate({URL: URL}, options).then(function (shortURL) { + var tinyUrl = [domain, "/", shortURL.hash].join(""); + console.log(["URL is ", shortURL.URL, " ", tinyUrl].join("")); + res.send(tinyUrl); + }, function (error) { + console.error(error.message); + res.send(500, 'Internal server error'); }); }); @@ -33,16 +35,18 @@ app.get('*', function (req, res) { var visitor = req.connection.remoteAddress, hash = req.url.slice(1), options = {visitor: visitor}; - short.retrieve(hash, options, function (error, shortURLObject) { - if (error) {console.error(error); + short.retrieve(hash, options).then(function (shortURLObject) { + if (shortURLObject) { + res.redirect(302, shortURLObject.URL); + } else { + res.send(404, 'URL not found!'); + } + }, function (error) { + console.error(error.message); + if (error instanceof Error && error.message.indexOf('Cannot find Document') !== -1) { + res.send(404, 'URL not found'); } else { - if (shortURLObject) { - res.redirect(shortURLObject.URL, 302); - } - else { - res.send('URL not found!', 404); - res.end(); - } + res.send(500, 'Internal server error'); } }); });