-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
40c4177
commit a38709b
Showing
5 changed files
with
918 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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/`); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); |
Oops, something went wrong.