-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
103 lines (89 loc) · 2.58 KB
/
server.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
require("dotenv").config();
const express = require("express");
const bodyParser = require("body-parser");
const path = require("path");
const { nanoid } = require("nanoid");
const mongoose = require("mongoose");
const Url = require("./models/Url"); // Import the Url model
const app = express();
const port = process.env.PORT || 3000;
app.use(bodyParser.json());
// Connect to MongoDB
let dbConnectionStatus = "disconnected";
mongoose
.connect(process.env.MONGODB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => {
dbConnectionStatus = "connected";
console.log("Connected to MongoDB");
})
.catch((error) => {
dbConnectionStatus = "error";
console.error("Error connecting to MongoDB:", error);
});
// Serve static files from the "src" directory
app.use(express.static(path.join(__dirname, "src")));
// Health check endpoint
app.get("/health", (req, res) => {
res.json({ status: dbConnectionStatus });
});
function generateShortenedUrl() {
const hash = nanoid(8); // Generate a unique ID of length 8
return hash;
}
// Root route
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, "src", "index.html"));
});
// Shorten URL route
app.post("/shorten", async (req, res) => {
try {
const originalUrl = req.body.url;
const hash = generateShortenedUrl();
const shortUrl = `${req.protocol}://${req.get("host")}/${hash}`; // Construct the full short URL
const newUrl = new Url({
originalUrl,
shortUrl,
hash,
createdAt: new Date(), // Ensure createdAt is set
});
await newUrl.save();
res.json({ shortUrl });
} catch (error) {
console.error("Error saving URL:", error);
res.status(500).send("Internal Server Error");
}
});
// Ad page route
app.get("/:hash", async (req, res) => {
try {
const url = await Url.findOne({ hash: req.params.hash });
if (url) {
res.sendFile(path.join(__dirname, "src", "views", "ad.html"));
} else {
res.status(404).send("Not Found");
}
} catch (error) {
console.error("Error finding URL:", error);
res.status(500).send("Internal Server Error");
}
});
// Redirect route
app.get("/redirect/:hash", async (req, res) => {
try {
const url = await Url.findOne({ hash: req.params.hash });
if (url) {
res.redirect(url.originalUrl);
} else {
res.status(404).send("Not Found");
}
} catch (error) {
console.error("Error finding URL:", error);
res.status(500).send("Internal Server Error");
}
});
app.listen(port, () => {
console.log(`URL shortener app listening at http://localhost:${port}`);
});