-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
105 lines (87 loc) · 2.42 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
104
105
const express = require("express")
const dotenv = require("dotenv")
const morgan = require("morgan")
const connectDB = require("./config/db")
const cors = require("cors")
const rateLimit = require("express-rate-limit")
const compression = require("compression")
const helmet = require("helmet")
const app = express()
app.use(express.json())
app.use(cors())
app.use(compression()) //Compress all routes
app.use(helmet())
// Server
dotenv.config({ path: "./config/config.env" })
const PORT = process.env.PORT || 8000
connectDB()
if (process.env.NODE_ENV === "development") {
app.use(morgan("dev"))
}
app.listen(PORT, () => {
console.log(`SERVER RUNNING IN ${process.env.NODE_ENV} ON PORT: ${PORT}`)
})
// CORS
app.use(cors())
// Rate limiting
const limiter = rateLimit({
windowMs: 10 * 60 * 1000,
max: 100,
})
app.use(limiter)
// Model
const Movie = require("./model")
// Middlware
const { advanceQuerying } = require("./middleware")
// Routes
// @desc Get a random movie
// @routes GET /random
// @access Public
app.get("/api/random", async (req, res) => {
try {
const result = await Movie.aggregate([
{
$sample: { size: 1 },
},
])
if (!result.length) {
return res
.status(400)
.json({ message: "Unable to find the resource" })
}
res.status(200).json(result[0])
} catch (error) {
res.status(400).json({ error: "Cannot fetch" })
}
})
// @desc Get/find movie by name
// @routes GET /movie/:name
// @access Public
app.get("/api/movie/:name", async (req, res) => {
try {
const result = await Movie.aggregate([
{
$match: { name: req.params.name },
},
]).collation({ locale: "en", strength: 2 })
if (!result.length) {
return res.status(400).json({
message:
"Oops, the requested movie does not exist in our database.",
})
}
res.status(200).json(result[0])
} catch (error) {
res.status(400).json({ error: "Cannot fetch" })
}
})
// @desc Get/find 10 movies sorted by IMDB rating
// @routes GET /movies
// @access Public
app.get("/api/movies/", advanceQuerying(Movie), async (req, res) => {
try {
res.status(200).json(res.advanceQuerying)
} catch (error) {
res.status(400).json({ error: "Cannot fetch" })
}
})