From 83bafe3f7f3764237d462327e140973eb239151f Mon Sep 17 00:00:00 2001 From: Sunny Dhoke Date: Fri, 9 Oct 2020 10:33:57 +0530 Subject: [PATCH] Added clicks abd ability to redirect to full url You can click on short or full url. Increments the count and updates in db. Sends 404 if null url. --- server.js | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/server.js b/server.js index c72c6fc..d64dce4 100644 --- a/server.js +++ b/server.js @@ -22,7 +22,7 @@ const ShortUrl = require("./models/shortUrl"); //get // index page with request and response parameters -// show all url in index page +// show all url from table "ShortUrl" in index page app.get("/", async (req, res) => { const shortUrls = await ShortUrl.find(); res.render("index", { shortUrls: shortUrls }); @@ -33,6 +33,25 @@ app.post("/shortUrls", async (req, res) => { ShortUrl.create({ full: req.body.fullUrl }); res.redirect("/"); }); + +//for clicking on short url after slash +//parameter ":shortUrl" +app.get("/:shortUrl", async (req, res) => { + //find the one where in "short", a "shortUrl" is found + const shortUrl = await ShortUrl.findOne({ short: req.params.shortUrl }); + + //if user sends empty shorturl,send 404 + if (shortUrl == null) return res.sendStatus(404); + + //otherwise increase the click + shortUrl.clicks++; + //save the changes in table + shortUrl.save(); + + //redirect the full link corresponding the short url we found + res.redirect(shortUrl.full); +}); + // start listening on specified port 4567 //can set as environment var app.listen(process.env.PORT || 4567);