-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
311 lines (238 loc) · 8.11 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
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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
const express = require('express');
const bcrypt = require('bcrypt');
const User = require('./User');
const router = express.Router();
// User registration route
router.post('/register', async (req, res) => {
const { username, password } = req.body;
try {
const existingUser = await User.findOne({ username });
if (existingUser) {
return res.status(400).send('Username already taken');
}
const newUser = new User({ username, password });
await newUser.save();
res.send('Registration successful!');
} catch (err) {
console.error('Registration error:', err);
res.status(500).send('Error during registration');
}
});
// User Login Route
router.post('/login', async (req, res) => {
const { username, password } = req.body;
try {
const user = await User.findOne({ username });
if (!user) {
return res.status(400).send('Invalid username');
}
const isMatch = await user.comparePassword(password);
if (!isMatch) {
return res.status(400).send('Invalid password');
}
res.status(200).json(user);
} catch (err) {
console.error('Login error:', err);
res.status(500).send('Error during login');
}
});
// Posting a new listing route
router.post('/new-listing', async (req, res) => {
const { title, description, minBidValue, username, imageBase64 } = req.body;
if (!title || !description || !minBidValue || !username || !imageBase64) {
return res.status(400).json({ message: 'All fields are required' });
}
try {
const user = await User.findOne({ username });
if (!user) {
return res.status(404).json({ message: 'User not found' });
}
const newListing = {
title,
description,
minBidValue: parseInt(minBidValue),
image: imageBase64,
};
user.listings.push(newListing);
await user.save();
const createdListing = user.listings[user.listings.length - 1];
res.status(200).json(createdListing);
} catch (err) {
console.error('Error creating listing:', err);
res.status(500).json({ message: 'Error creating listing' });
}
});
// Retreives all active listings on the website
router.get('/all-listings', async (req, res) => {
try {
const users = await User.find();
const allListings = users.reduce((acc, user) => {
return acc.concat(user.listings);
}, []);
res.json(allListings);
} catch (err) {
console.error('Error retrieving listings:', err);
res.status(500).send('Error retrieving listings');
}
});
// Route all active listings for a specific user
router.get('/my-listings', async (req, res) => {
const { username } = req.query;
if (!username) {
return res.status(400).send('Username is required');
}
try {
const user = await User.findOne({ username });
if (!user) {
return res.status(404).send('User not found');
}
res.json(user.listings);
} catch (err) {
console.error('Error retrieving user listings:', err);
res.status(500).send('Error retrieving listings');
}
});
// Delete a listing route
router.delete('/delete-listing', async (req, res) => {
const { username, listingId } = req.body;
if (!username || !listingId) {
return res.status(400).send('Username and listingId are required');
}
try {
const user = await User.findOne({ username });
if (!user) {
return res.status(404).send('User not found');
}
const listingIndex = user.listings.findIndex(listing => listing._id.toString() === listingId);
if (listingIndex === -1) {
return res.status(404).send('Listing not found');
}
user.listings.splice(listingIndex, 1);
await user.save();
res.send('Listing deleted successfully');
} catch (err) {
console.error('Error deleting listing:', err);
res.status(500).send('Error deleting listing');
}
});
// Route to post a bid
router.post('/post-bid', async (req, res) => {
const { username, listingId, bidValue } = req.body;
if (!username || !listingId || !bidValue) {
return res.status(400).send('Username, listingId, and bidValue are required');
}
try {
const userWithListing = await User.findOne({ 'listings._id': listingId });
if (!userWithListing) {
return res.status(404).send('Listing not found');
}
const listing = userWithListing.listings.id(listingId);
if (!listing) {
return res.status(404).send('Listing not found');
}
if (userWithListing.username === username) {
return res.status(403).send('You cannot bid on your own listing');
}
if (listing.bids.length === 0) {
if (bidValue < listing.minBidValue) {
return res.status(400).send(`First bid must be greater than the minimum bid value of ${listing.minBidValue}`);
}
} else {
const highestBid = listing.bids.reduce((maxBid, currentBid) => {
return currentBid.bidValue > maxBid.bidValue ? currentBid : maxBid;
}, { bidValue: 0 });
if (bidValue <= highestBid.bidValue) {
return res.status(400).send(`Bid value must be higher than the current highest bid of ${highestBid.bidValue}`);
}
}
const newBid = {
bidValue: Number(bidValue),
username: String(username)
};
listing.bids.push(newBid);
const validationError = userWithListing.validateSync();
if (validationError) {
console.error('Validation Error:', validationError);
return res.status(400).send(`Validation Error: ${validationError.message}`);
}
await userWithListing.save();
res.send('Bid placed successfully');
} catch (err) {
console.error('Error placing bid:', err);
res.status(500).send('Error placing bid');
}
});
// Selling an item route
router.post('/sell-item', async (req, res) => {
const { sellerUsername, listingId } = req.body;
if (!sellerUsername || !listingId) {
return res.status(400).send('Seller username and listingId are required');
}
try {
const seller = await User.findOne({ username: sellerUsername });
if (!seller) {
return res.status(404).send('Seller not found');
}
const listing = seller.listings.id(listingId);
if (!listing) {
return res.status(404).send('Listing not found for this seller');
}
if (listing.bids.length === 0) {
return res.status(400).send('No bids available for this listing');
}
const highestBid = listing.bids.reduce((max, bid) => (bid.bidValue > max.bidValue ? bid : max), listing.bids[0]);
listing.sold = true;
listing.soldTo = highestBid.username;
listing.soldPrice = highestBid.bidValue;
await seller.save();
res.status(200).json({
message: 'Item sold successfully',
listingId: listingId,
soldTo: highestBid.username,
soldPrice: highestBid.bidValue
});
} catch (err) {
console.error('Error selling item:', err);
res.status(500).send('Error selling item');
}
});
// Route to get all items bought by a specific user
router.get('/bought-by-me', async (req, res) => {
const { username } = req.query;
if (!username) {
return res.status(400).json({ error: 'Username is required' });
}
try {
const users = await User.find();
if (!users || users.length === 0) {
return res.status(200).json([]);
}
const boughtListings = users.flatMap(user =>
user.listings.filter(listing => listing.soldTo === username)
);
res.status(200).json(boughtListings);
} catch (err) {
console.error('Error retrieving bought items:', err);
res.status(500).json({ error: 'Error retrieving bought items' });
}
});
// Route to get all items sold by a specific user
router.get('/sold-by-me', async (req, res) => {
const { username } = req.query;
if (!username) {
return res.status(400).json({ error: 'Username is required' });
}
try {
const user = await User.findOne({ username });
if (!user) {
return res.status(404).json({ error: 'User not found' });
}
const soldListings = user.listings.filter(listing => listing.sold);
res.status(200).json(soldListings);
} catch (err) {
console.error('Error retrieving sold items:', err);
res.status(500).json({ error: 'Error retrieving sold items' });
}
});
// Export routes
module.exports = router;