-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
71 lines (60 loc) · 1.62 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
const express = require("express");
const ejsMate = require("ejs-mate");
const AppError = require("./AppError");
const { extractData } = require("./utlis");
const app = express();
const port = 3000;
//middleware for public files such as: images,css and js
app.use(express.static("public"));
// parse url/encoded data for body
app.use(express.urlencoded({ extended: true }));
// use ejs-locals for all ejs templates:
app.engine("ejs", ejsMate);
// Set View Engine
app.set("views", __dirname + "/views");
app.set("view engine", "ejs");
// Home page
app.get("/", (req, res) => {
res.render("index");
});
// About page
app.get("/about", (req, res) => {
res.render("about");
});
// Show Data
app.post("/show", async (req, res, next) => {
try {
const { urls } = req.body;
// Check if urls exists
if (!urls) throw new AppError(400, "Urls are not submitted");
// Extract urls
const imdbUrls = urls.split(",").filter((url) => url !== "");
// Extract data from urls
const data = await extractData(imdbUrls);
res.render("show", { data });
} catch (error) {
next(error);
}
});
// Download file - with no validation!
app.post("/download", (req, res) => {
res.download("./data/imdb_data.csv");
});
// 404 handler
app.all("*", (req, res, next) => {
next(new AppError(404, "Page Not Found"));
});
// Error Handler
app.use((err, req, res, next) => {
const { statusCode = 500, message = "try again later" } = err;
res.render("error", {
error: {
statusCode,
message,
stack: err.stack,
},
});
});
app.listen(port, () => {
console.log(`server listening on http://localhost:${port}`);
});