var express = require('express');
var bodyParser = require('body-parser');
var app = express();

var slug = require('shortid');
var mongoose = require('mongoose');
var config = require('./config');

var Url = require('./urlModel');

mongoose.connect('mongodb://' + config.db.host + '/' + config.db.name, {
  useMongoClient: true,
});

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: true
}));

app.get('/', function(req, res) {
  res.send('Welcome to Shortly');
});

app.post('/api/shorten', function(req, res) {
  let url = req.body.url;
  let newSlug = slug.generate();

  var newUrl = Url({
    long: url,
    short: newSlug
  });

  newUrl.save(function(err) {
    if (err) {
      console.log(err);
    }
  });
    
  res.send({ shortenedURL: `http://localhost:4000/${newSlug}` });
  
});





app.listen(process.env.PORT || 4000);
@@ -812,16 +812,1341 @@
   %0A%7D);%0A%0A
+app.get('/:slug', function(req, res) %7B%0A  let short = req.params.slug;%0A  let currentDate;%0A  const msToDays = 1000 * 60 * 60 * 24;%0A  console.log('short: ', short);%0A  Url.findOne(%7Bshort%7D, function (err, doc) %7B%0A    if (doc) %7B%0A      res.redirect(302, 'http://' + doc.long);%0A      console.log(req.query.testDate);%0A      if ( !req.query.testDate ) %7B%0A        currentDate = new Date();%0A        console.log(currentDate);%0A      %7D else %7B%0A        currentDate = new Date(req.query.testDate);%0A%0A      %7D%0A      doc.allTime++;%0A      let length = doc.lastSeven.length;%0A      if ( length === 0 ) %7B %0A        doc.lastSeven.push(%7B count: 1, date: currentDate%7D);%0A      %7D else %7B%0A        %0A        length = doc.lastSeven.length;%0A        let lastDay = doc.lastSeven%5Blength - 1%5D;%0A        let lastDate = new Date(lastDay.date);%0A        let diff = ( currentDate - lastDate ) / msToDays;%0A        if ( diff %3E 1 ) %7B%0A          doc.lastSeven.push(%7B count: 1, date: currentDate%7D);%0A        %7D else %7B%0A          console.log('i was here');%0A          lastDay.count++;%0A        %7D%0A        length = doc.lastSeven.length;%0A        if ( length %3E 7 ) %7B%0A          doc.lastSeven.shift();%09%0A        %7D %0A      %7D %0A%0A      doc.save(function(err) %7B%0A        if (err) %7B%0A          console.log(err);%0A        %7D%0A      %7D);%0A      %0A    %7D else %7B%0A      res.redirect(config.host);%0A    %7D%0A  %7D);%0A  %0A%7D);
 %0A%0A%0A%0Aapp.

add short url roule with redirect and stats data update