-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
53 lines (44 loc) · 1.5 KB
/
index.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
require("dotenv").config();
const express = require("express");
const path = require("path");
const cookieParser = require("cookie-parser");
const { connectToMongoDB } = require("./connect");
const { checkForAuthentication, restrictTo } = require("./middlewares/auth");
const URL = require("./models/url");
const urlRoute = require("./routes/url");
const staticRoute = require("./routes/staticRouter");
const userRoute = require("./routes/user");
const app = express();
const PORT = 8001;
// Debugging: Log the DATABASE_URI
console.log("Loaded DATABASE_URI:", process.env.DATABASE_URI);
connectToMongoDB(process.env.DATABASE_URI).then(() =>
console.log("Mongodb Connected!")
);
app.set("view engine", "ejs");
app.set("views", path.resolve("./views")); //all files of ejs are in views folder
//Middleware so that it parse the incoming body
app.use(express.json());
app.use(express.urlencoded({ extended: false })); //It means we will support JSON data and form data as well
app.use(cookieParser());
app.use(checkForAuthentication);
app.use("/url", restrictTo(["NORMAL", "ADMIN"]), urlRoute);
app.use("/user", userRoute);
app.use("/", staticRoute);
app.get("/url/:shortId", async (req, res) => {
const shortId = req.params.shortId;
const entry = await URL.findOneAndUpdate(
{
shortId,
},
{
$push: {
visitHistory: {
timestamp: Date.now(),
},
},
}
);
res.redirect(entry.redirectURL);
});
app.listen(PORT, () => console.log(`Server started at PORT: ${PORT}`));