-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
162 lines (142 loc) · 5.06 KB
/
server.js
File metadata and controls
162 lines (142 loc) · 5.06 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
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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
const express = require('express');
const app = express();
const { MongoClient, ObjectId } = require('mongodb');
const path = require('path');
const bodyParser = require('body-parser');
const open = require('open');
// ---- 1. MongoDB connection string ----
const uri = "mongodb+srv://s3710021:Test1234@dba-cluster.jpcdrgc.mongodb.net/sample_airbnb?retryWrites=true&w=majority&appName=DBA-Cluster";
const client = new MongoClient(uri);
// ---- 2. Express Middleware ----
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(express.static('public')); // Serve static files (index.html, etc.)
// ---- 3. Start server AFTER DB connects ----
async function startServer() {
try {
await client.connect();
console.log("Connected to MongoDB");
// ---- 4. API Endpoint: Search Listings ----
app.get('/api/listings', async (req, res, next) => {
try {
const db = client.db("sample_airbnb");
const collection = db.collection("listingsAndReviews");
const filter = {};
// If id is given, return only that listing (for bookings page)
if (req.query.id) {
const id = req.query.id;
let objId;
try {
objId = id.length === 24 ? new ObjectId(id) : id;
} catch {
objId = id; // fallback if not an ObjectId
}
const listing = await collection.find({ _id: objId }, {
projection: {
name: 1,
summary: 1,
price: 1,
"review_scores.review_scores_rating": 1,
_id: 1
}
}).toArray();
return res.json(listing);
}
// --- RANDOM listings if no filters provided (homepage load) ---
if (!req.query.location && !req.query.propertyType && !req.query.bedrooms) {
const listings = await collection.aggregate([
{ $sample: { size: 10 } },
{
$project: {
name: 1,
summary: 1,
price: 1,
"review_scores.review_scores_rating": 1,
_id: 1
}
}
]).toArray();
return res.json(listings);
}
// Otherwise, use filters for search
if (req.query.location) {
filter['address.market'] = { $regex: req.query.location, $options: 'i' };
}
if (req.query.propertyType) {
filter.property_type = req.query.propertyType;
}
if (req.query.bedrooms) {
if (req.query.bedrooms === '5plus') {
filter.bedrooms = { $gte: 5 };
} else {
filter.bedrooms = parseInt(req.query.bedrooms);
}
}
// Filtered search (sorted by rating, max 20)
const listings = await collection.find(filter, {
projection: {
name: 1,
summary: 1,
price: 1,
"review_scores.review_scores_rating": 1,
_id: 1
}
})
.sort({ "review_scores.review_scores_rating": -1 })
.limit(20)
.toArray();
res.json(listings);
} catch (err) {
next(err);
}
});
// ---- 5. API endpoint: handle booking form POST ----
app.post('/api/bookings', async (req, res, next) => {
try {
const booking = req.body;
const db = client.db("sample_airbnb");
const bookingsCol = db.collection("bookings");
// Make sure startDate and endDate are present
if (!booking.startDate || !booking.endDate) {
return res.json({ success: false, error: "Missing start or end date." });
}
// Convert to ISO strings to ensure proper comparison
const newStart = new Date(booking.startDate);
const newEnd = new Date(booking.endDate);
// Check for overlapping bookings for the same listing
const overlap = await bookingsCol.findOne({
listing_id: booking.listing_id,
startDate: { $lte: booking.endDate },
endDate: { $gte: booking.startDate }
});
if (overlap) {
return res.json({
success: false,
error: "The selected dates overlap with an existing booking for this property. Please choose another date range."
});
}
// No overlap, insert the new booking
await bookingsCol.insertOne(booking);
res.json({ success: true });
} catch (err) {
res.json({ success: false, error: err.message });
}
});
// ---- 6. Error Handlers ----
app.use((req, res, next) => res.status(404).send("Not found"));
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send("Internal Server Error");
});
// ---- 7. Start Listening and Open Browser ----
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server listening on port ${PORT}`);
open(`http://localhost:${PORT}`);
});
} catch (err) {
console.error("Failed to connect to MongoDB", err);
process.exit(1);
}
}
startServer();