-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
115 lines (104 loc) · 2.51 KB
/
index.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
const Hapi = require("@hapi/hapi");
const Mongoose = require("mongoose");
Mongoose.connect(
"<YOUR-MONGODB-CONNECTION-STRING>",
{ useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false }
)
.then(() => {
console.log("Database Connected");
return true;
})
.catch((err) => {
console.error("Error : Cannot connect to Database " + err);
return false;
});
const MovieModel = Mongoose.model("movies", {
name: String,
year: Number,
plot: String,
});
const init = async () => {
const server = Hapi.server({
port: process.env.PORT || 3000,
host: "localhost",
});
server.route({
method: "GET",
path: "/",
handler: (request, h) => {
return "Welcome To Movies API!!";
},
});
server.route({
method: "POST",
path: "/addMovie",
handler: async (request, h) => {
try {
const newMovie = new MovieModel(request.payload);
const result = await newMovie.save();
return h.response(result);
} catch (error) {
return h.response(error).code(500);
}
},
});
server.route({
method: "GET",
path: "/movies",
handler: async (request, h) => {
try {
const movies = await MovieModel.find().exec();
return h.response(movies);
} catch (error) {
return h.response(error).code(500);
}
},
});
server.route({
method: "GET",
path: "/movie/{id}",
handler: async (request, h) => {
try {
const movie = await MovieModel.findById(request.params.id).exec();
return h.response(movie);
} catch (error) {
return h.response(error).code(500);
}
},
});
server.route({
method: "PUT",
path: "/movie/{id}",
handler: async (request, h) => {
try {
const result = await MovieModel.findByIdAndUpdate(
request.params.id,
request.payload,
{ new: true }
);
return h.response(result);
} catch (error) {
return h.response(error).code(500);
}
},
});
server.route({
method: "DELETE",
path: "/movie/{id}",
handler: async (request, h) => {
try {
const result = await MovieModel.findByIdAndDelete(request.params.id);
return h.response(result);
} catch (error) {
return h.response(error).code(500);
}
},
});
await server.start();
console.log("Server running on %s", server.info.uri);
};
process.on("unhandledRejection", (err) => {
console.log(err);
process.exit(1);
});
init();