-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtoursAPI.js
More file actions
executable file
·110 lines (98 loc) · 2.6 KB
/
toursAPI.js
File metadata and controls
executable file
·110 lines (98 loc) · 2.6 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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
//create MongoClient const
const MongoClient = require('mongodb').MongoClient;
//create Hapi const
const Hapi = require('hapi');
//create server const
const server = new Hapi.Server();
//connect server to port
server.connection({
port: 8080
});
server.route([
//Homepage
{
method: 'GET',
path: '/',
handler: (request, reply) => {
reply('Hello World');
}
},
//Display all tours
{
method: 'GET',
path: '/api/tours',
handler: (request, reply) => {
const userSearch = {};
for (const key in request.query) {
userSearch[key] = request.query[key];
}
collection.find(userSearch).toArray((error, tours) => {
reply(tours);
});
}
},
//Display one tour
{
method: 'GET',
path: '/api/tours/{name}',
handler: (request, reply) => {
collection.findOne({ tourName: request.params.name }, (error, tour) => {
reply(tour);
});
}
},
//create a new tour
//request.payload contains all fields and values sent by the client
{
method: 'POST',
path: '/api/tours',
handler: (request, reply) => {
collection.insertOne(request.payload, (error, result) => {
reply(request.payload);
});
}
},
//update a single tour
{
method: 'PUT',
path: '/api/tours/{name}',
handler: (request, reply) => {
if (request.query.replace == 'true') {
request.payload.tourName = request.params.name;
collection.replaceOne({ tourName: request.params.name }, request.payload, (error, results) => {
collection.findOne({ tourName: request.params.name }, (error, results) => {
reply(results);
});
});
} else {
collection.updateOne({ tourName: request.params.name }, { $set: request.payload }, (error, results) => {
collection.findOne({ tourName: request.params.name }, (error, results) => {
reply(results);
});
});
}
}
},
//Delete Single Tour
{
method: 'DELETE',
path: '/api/tours/{name}',
handler: (request, reply) => {
collection.deleteOne({ tourName: request.params.name }, (error, results) => {
reply().code(204);
});
}
}
]);
//this is using the mongodb package
const url = 'mongodb://localhost:27017/learning_mongo';
MongoClient.connect(url, function(err, db) {
//show user server connected successfuly
console.log('Successfully Connected to Server');
//collection tours
collection = db.collection('tours');
//start server
server.start(function(err) {
console.log('Hapi is listening to http://localhost:8080');
});
});