-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
74 lines (62 loc) · 1.72 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import express from "express";
import mongoose from "mongoose";
import dotenv from 'dotenv';
if (process.env.NODE_ENV !== 'production')
dotenv.config()
// importing database schema model
import ShortURL from "./models/url.js";
const app = express();
app.use(express.urlencoded({ extended: false }));
app.set("view engine", "ejs");
app.use(express.static('./views'));
// routes
app.get("/", async (req, res) => {
const allData = await ShortURL.find({}, { _id: 0 });
res.render("index", {
shortUrls: allData,
});
});
app.post("/short", async (req, res) => {
// Grabbing fullUrl from req.body
const url = req.body.fullUrl;
const record = new ShortURL({
full: url,
});
await record.save();
res.redirect("/");
});
// shortid request route
app.get("/:shortid", async (req, res) => {
// grabbing data from req
const shortid = req.params.shortid;
// finding the document
const data = await ShortURL.findOne({ short: shortid });
if (!data) {
return res.sendStatus(404);
}
// update clicks if data is not null
data.clicks++;
// save the data to db
await data.save();
// redirect user to original link
res.redirect(data.full);
});
// database connection
const driverUrl = process.env.MONGODB_KEY;
const connectionParams = {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true,
};
mongoose
.connect(driverUrl, connectionParams)
.then(() => {
console.log("Connected to database ");
})
.catch((err) => {
console.error(`Error connecting to the database. \n${err}`);
});
// Listening for incoming requests on successful connection to MongoAtlas
mongoose.connection.on("open", () => {
app.listen(process.env.PORT || "3000", () => console.log(`Server Running`));
});