Skip to content

Commit

Permalink
basic functionality added
Browse files Browse the repository at this point in the history
  • Loading branch information
HaseebUllahAbbasi committed Jun 14, 2022
1 parent 40c4177 commit a38709b
Show file tree
Hide file tree
Showing 5 changed files with 918 additions and 0 deletions.
38 changes: 38 additions & 0 deletions app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
const express = require("express");
const mongoose = require("mongoose");
const ShortUrl = require("./models/shortUrl");
const app = express();

mongoose.connect("mongodb://localhost/urlShortener", {
useNewUrlParser: true,
useUnifiedTopology: true,
});

app.set("view engine", "ejs");
app.use(express.urlencoded({ extended: false }));

app.get("/", async (req, res) => {
const shortUrls = await ShortUrl.find();
res.render("index", { shortUrls: shortUrls });
});

app.post("/shortUrls", async (req, res) => {
await ShortUrl.create({ full: req.body.fullUrl });

res.redirect("/");
});

app.get("/:shortUrl", async (req, res) => {
const shortUrl = await ShortUrl.findOne({ short: req.params.shortUrl });
if (shortUrl == null) return res.sendStatus(404);

shortUrl.clicks++;
shortUrl.save();

res.redirect(shortUrl.full);
});

app.listen(4000, () => {
console.log(`server started on port 4000
Click on the link : http://localhost:4000/`);
});
20 changes: 20 additions & 0 deletions models/shortUrl.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
const mongoose = require("mongoose");
const shortId = require("shortid");
const shortUrlSchema = new mongoose.Schema({
full: {
type: String,
required: [true, "please enter the full url"],
},
short: {
type: String,
required: [true, "please enter the short url"],
default: shortId.generate,
},
clicks: {
type: Number,
required: true,
default: 0,
},
});

module.exports = mongoose.model("ShortUrl", shortUrlSchema);
Loading

0 comments on commit a38709b

Please sign in to comment.