-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
141 lines (119 loc) · 3.38 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
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
const path = require("path");
const viewRouter = require("./Routes/viewRoutes");
const userRouter = require("./Routes/userRoutes");
const authcontroller = require("./controllers/authcontroller");
const User = require("./models/userModel");
const express = require("express");
const rateLimit = require("express-rate-limit");
const shortid = require("shortid");
const validUrl = require("valid-url");
const URLSchema = require("./models/shorturlsModel");
const mongoose = require("mongoose");
const dotenv = require("dotenv");
const cookieParser = require("cookie-parser");
const globalErrorHandler = require("./controllers/errorController");
const { createClient } = require("redis");
dotenv.config({ path: "./config.env" });
const client = createClient({
password: process.env.REDISPASSWORD,
socket: {
host: "redis-14029.c8.us-east-1-4.ec2.cloud.redislabs.com",
port: 14029,
},
});
client.on("error", (err) => console.log("Redis Client Error", err));
async function main() {
await client.connect();
}
main().catch((err) => console.error(err));
const app = express();
app.use(express.json());
app.set("view engine", "pug");
app.set("views", path.join(__dirname, "views"));
app.use(express.static(path.join(__dirname, "public")));
app.use(cookieParser());
const limiter = rateLimit({
max: 10,
windowMs: 60 * 60 * 1000,
message:
"User is allowed to make only 10 requests per hour, please try again in an hour",
});
app.use("/", viewRouter);
app.use("/api", limiter);
app.post("/short", authcontroller.protect, async (req, res) => {
const originalUrl = req.body.url;
const URL = await URLSchema.findOne({
originalUrl: originalUrl,
});
console.log("URL", URL);
if (!URL) {
if (validUrl.isUri(req.body.url)) {
const shortUrl = shortid.generate();
const newURL = await URLSchema.create({
originalUrl: originalUrl,
url: shortUrl,
});
console.log(res.locals.user._id);
const curruser = await User.findById(res.locals.user._id);
curruser.urls.push(newURL._id);
await curruser.save({
validateBeforeSave: false,
});
await client.set(shortUrl, originalUrl);
return res.json({
status: "success",
data: {
newURL,
},
});
} else {
return res.send("Please provide a valid url");
}
}
res.json({
status: "success",
data: {
URL,
},
});
});
app.get("/:url", async (req, res) => {
// decode and redirect url
try {
let url = await client.get(req.params.url);
console.log(url);
if (url) {
console.log("URL Found", url);
return res.redirect(url);
}
console.log(url);
url = await URLSchema.findOne({ url: req.params.url });
if (url !== null) {
return res.redirect(url.originalUrl);
} else {
res.send("invalid/expired URL");
}
} catch (e) {
console.log(e);
res.send("invalid/expired URL");
}
});
app.use("/api/v1/users", userRouter);
app.all("*", (req, res, next) => {
next(new Error(`Can't find ${req.originalUrl} on this server}`, 404));
});
mongoose
.connect(process.env.DATABASE, {
useNewUrlParser: true,
})
.then((con) => {
console.log("DB connection successful");
})
.catch((err) => {
console.log(err);
});
const port = process.env.PORT || 3000;
app.use(globalErrorHandler);
app.listen(port, () => {
console.log(`App running on port ${port}`);
});