-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathapp.js
More file actions
92 lines (77 loc) · 2.44 KB
/
app.js
File metadata and controls
92 lines (77 loc) · 2.44 KB
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
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const helmet = require("helmet");
const cors = require("cors");
const url = require("./routes/api/url");
const users = require("./routes/api/users");
const auth = require("./routes/api/auth");
const Url = require("./models/url");
const app = express();
app.use(cors());
app.use(helmet.permittedCrossDomainPolicies());
app.use(helmet.xssFilter());
app.use(helmet.dnsPrefetchControl({ allow: true }));
app.use(helmet.frameguard({ action: "sameorigin" }));
app.use(helmet.hidePoweredBy({ setTo: "your dummy tech" }));
app.use(helmet.hsts({ maxAge: 2592000 })); //30 days max age
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// require("dotenv").config();
mongoose
.connect(
`mongodb+srv://${process.env.MONGO_USER}:${process.env.MONGO_PASSWORD}@cluster0-jwfcs.mongodb.net/${process.env.MONGO_DB}?retryWrites=true&w=majority`,
{
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
}
)
.then(() => {
console.log("MongoDb connected.....");
})
.catch((err) => {
console.log("Cannot connect to db due to " + err);
});
app.use("/api/urls", url);
app.use("/api/register", users);
app.use("/api/login", auth);
app.get("/:code", async (req, res) => {
try {
const url = await Url.findOne({ code: req.params.code });
if (url) {
if (
url.lastDate &&
url.lastDate.toISOString() < new Date().toISOString()
) {
const user = await User.findById(url.creator);
for (let i = 0; i < user.shortenedUrl.length; i++) {
if (user.shortenedUrl[i].toString() === id) {
user.shortenedUrl.splice(i, 1);
break;
}
}
await user.save();
await url.deleteOne();
return res
.status(404)
.json({ msg: "This Compress URL does not exist any more!" });
}
if (!url.status) {
return res
.status(404)
.json({ msg: "This url is temporarily out of service!" });
}
url.clicks = url.clicks + 1;
url.save();
return res.redirect(url.longUrl);
} else {
return res.status(404).json({ msg: "No Compressed URL Found" });
}
} catch (err) {
console.log(err);
res.status(500).json({ msg: "Internal Server Error" });
}
});
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server Started on port ${port}`));