SHARE
TWEET

Untitled

a guest May 5th, 2016 150 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var express = require('express');
  2. var router = express.Router();
  3.  
  4. var mongodb = require('mongodb');
  5. var mLab = "mongodb://localhost:27017/url-shortener-microservice";
  6. var MongoClient = mongodb.MongoClient
  7.  
  8. var shortid = require('shortid');
  9. var validUrl = require('valid-url');
  10.  
  11. /* GET home page. */
  12. router.get('/', function(req, res, next) {
  13.   res.render('index', { title: 'Express' });
  14. });
  15.  
  16. router.get('/new/:url(*)', function (req, res, next) {
  17.   MongoClient.connect(mLab, function (err, db) {
  18.     if (err) {
  19.       console.log("Unable to connect to server", err);
  20.     } else {
  21.       console.log("Connected to server")
  22.      
  23.       var collection = db.collection('links');
  24.       var params = req.params.url;
  25.      
  26.       var newLink = function (db, callback) {
  27.         if (validUrl.isUri(params)) {
  28.           // if URL is valid, do this
  29.           var shortCode = shortid.generate();
  30.           var newUrl = { url: params, short: shortCode };
  31.           collection.insert([newUrl]);
  32.           res.json({ original_url: params, short_url: "localhost:3000/" + shortCode });
  33.         } else {
  34.          // if URL is invalid, do this
  35.           res.json({ error: "Wrong url format, make sure you have a valid protocol and real site." });
  36.         };
  37.       };
  38.      
  39.       newLink(db, function () {
  40.         db.close();
  41.       });
  42.      
  43.     };
  44.   });
  45.  
  46. });
  47.  
  48. module.exports = router;
RAW Paste Data
Top