-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
487 lines (425 loc) · 14.9 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
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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
const express = require("express");
const app = express();
const cors = require("cors");
require("dotenv").config();
const jwt = require("jsonwebtoken");
const stripe = require("stripe")(process.env.STRIPE_SECRET_KEY);
const formData = require("form-data");
// const Mailgun = require("mailgun.js");
// const mailgun = new Mailgun(formData);
// const mg = mailgun.client({
// username: "api",
// key: process.env.MAILGUN_API_KEY,
// });
const port = process.env.PORT || 3000;
// Middleware
app.use(cors());
app.use(express.json());
const { MongoClient, ServerApiVersion, ObjectId } = require("mongodb");
const uri = `mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASS}@cluster0.x53s3dr.mongodb.net/?appName=Cluster0`;
// Create a MongoClient with a MongoClientOptions object to set the Stable API version
const client = new MongoClient(uri, {
serverApi: {
version: ServerApiVersion.v1,
strict: true,
deprecationErrors: true,
},
});
async function run() {
try {
// Connect the client to the server (optional starting in v4.7)
await client.connect();
const userCollection = client.db("bistroDB").collection("users");
const menuCollection = client.db("bistroDB").collection("menu");
const reviewCollection = client.db("bistroDB").collection("reviews");
const cartCollection = client.db("bistroDB").collection("carts");
const bookingCollection = client.db("bistroDB").collection("bookings");
const paymentCollection = client.db("bistroDB").collection("payments");
const messageCollection = client.db("bistroDB").collection("messages");
// JWT related API
app.post("/jwt", async (req, res) => {
const user = req.body;
const token = jwt.sign(user, process.env.ACCESS_TOKEN_SECRET, {
expiresIn: "1h",
});
res.send({ token });
});
// Middlewares
const verifyToken = (req, res, next) => {
// console.log("Inside verifyToken:", req.headers.authorization);
if (!req.headers.authorization) {
return res.status(401).send({ message: "Unauthorized Access!" });
}
const token = req.headers.authorization.split(" ")[1];
jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, decoded) => {
if (err) {
return res.status(401).send({ message: "Unauthorized Access!" });
}
req.decoded = decoded;
next();
});
};
// use verifyAdmin after verifyToken
const verifyAdmin = async (req, res, next) => {
const email = req.decoded.email;
const query = { email: email };
const user = await userCollection.findOne(query);
const isAdmin = user?.role === "admin";
if (!isAdmin) {
return res.status(403).send({ message: "Forbidden Access!" });
}
next();
};
// User Related API
app.get("/users", verifyToken, verifyAdmin, async (req, res) => {
const result = await userCollection.find().toArray();
res.send(result);
});
app.get("/users/admin/:email", verifyToken, async (req, res) => {
const email = req.params.email;
if (email !== req.decoded.email) {
return res.status(403).send({ message: "Forbidden Access!" });
}
const query = { email: email };
const user = await userCollection.findOne(query);
let admin = false;
if (user) {
admin = user?.role === "admin";
}
res.send({ admin });
});
app.post("/users", async (req, res) => {
const user = req.body;
// Insert email if user does not exist
const query = { email: user.email };
const existingUser = await userCollection.findOne(query);
if (existingUser) {
return res.send({ message: "User already exists", insertedId: null });
}
const result = await userCollection.insertOne(user);
res.send(result);
});
app.patch(
"/users/admin/:id",
verifyToken,
verifyAdmin,
async (req, res) => {
const id = req.params.id;
const filter = { _id: new ObjectId(id) };
const updatedDoc = {
$set: {
role: "admin",
},
};
const result = await userCollection.updateOne(filter, updatedDoc);
res.send(result);
}
);
app.delete("/users/:id", verifyToken, verifyAdmin, async (req, res) => {
const id = req.params.id;
const query = { _id: new ObjectId(id) };
const result = await userCollection.deleteOne(query);
res.send(result);
});
// Menu related API
app.get("/menu", async (req, res) => {
const result = await menuCollection.find().toArray();
res.send(result);
});
app.get("/menu-names", async (req, res) => {
const result = await menuCollection
.find(
{},
{
projection: {
_id: 0,
name: 1,
},
}
)
.toArray();
res.send(result);
});
app.get("/menu/:id", async (req, res) => {
const id = req.params.id;
const query = { _id: new ObjectId(id) };
const result = await menuCollection.findOne(query);
res.send(result);
});
app.post("/menu", verifyToken, verifyAdmin, async (req, res) => {
const item = req.body;
const result = await menuCollection.insertOne(item);
res.send(result);
});
app.patch("/menu/:id", verifyToken, verifyAdmin, async (req, res) => {
const id = req.params.id;
const item = req.body;
const filter = { _id: new ObjectId(id) };
const updateDoc = {
$set: {
name: item.name,
recipe: item.recipe,
image: item.image,
category: item.category,
price: item.price,
},
};
const result = await menuCollection.updateOne(filter, updateDoc);
res.send(result);
});
app.delete("/menu/:id", verifyToken, verifyAdmin, async (req, res) => {
const id = req.params.id;
const query = { _id: new ObjectId(id) };
const result = await menuCollection.deleteOne(query);
res.send(result);
});
// Reviews Related API
app.get("/reviews", async (req, res) => {
const result = await reviewCollection.find().toArray();
res.send(result);
});
app.get("/reviews/:name", async (req, res) => {
const name = req.params.name;
const query = {menuName: name};
const result = await reviewCollection.find(query).toArray();
res.send(result);
})
app.post("/reviews", async (req, res) => {
const review = req.body;
const result = await reviewCollection.insertOne(review);
res.send(result);
});
// Bookings related API
app.get("/bookings", verifyToken, verifyAdmin, async (req, res) => {
const result = await bookingCollection.find().toArray();
res.send(result);
});
app.get("/bookings/:email", verifyToken, async (req, res) => {
const email = req.params.email;
if (req.params.email !== req.decoded.email) {
return res.status(403).send({ message: "Forbidden Access" });
}
const query = { email: email };
const result = await bookingCollection.find(query).toArray();
res.send(result);
});
app.patch("/bookings/:id", async (req, res) => {
const id = req.params.id;
const status = req.body.status;
const newStatus =
status === "confirm" ? "confirmed" : "Sorry, Out of space!";
const filter = { _id: new ObjectId(id) };
const updateBooking = {
$set: {
status: newStatus,
},
};
const result = await bookingCollection.updateOne(filter, updateBooking);
res.send(result);
});
app.delete("/bookings/:id", async (req, res) => {
const id = req.params.id;
const query = { _id: new ObjectId(id) };
const result = await bookingCollection.deleteOne(query);
res.send(result);
});
app.post("/bookings", verifyToken, async (req, res) => {
const booking = req.body;
const result = await bookingCollection.insertOne(booking);
res.send(result);
});
// Cart Related API
app.get("/carts", async (req, res) => {
const email = req.query.email;
const query = { email: email };
const result = await cartCollection.find(query).toArray();
res.send(result);
});
app.post("/carts", async (req, res) => {
const cartItem = req.body;
const result = await cartCollection.insertOne(cartItem);
res.send(result);
});
app.delete("/carts/:id", async (req, res) => {
const id = req.params.id;
const query = { _id: new ObjectId(id) };
const result = await cartCollection.deleteOne(query);
res.send(result);
});
// Payment Intent and payment related API
app.get("/payments", async (req, res) => {
const result = await paymentCollection.find().toArray();
res.send(result);
});
app.get("/payments/:email", verifyToken, async (req, res) => {
const query = { email: req.params.email };
if (req.params.email !== req.decoded.email) {
return res.status(403).send({ message: "Forbidden Access" });
}
const result = await paymentCollection.find(query).toArray();
res.send(result);
});
app.patch("/payments/:id", async (req, res) => {
const id = req.params.id;
const status = req.body.status;
const filter = { _id: new ObjectId(id) };
const updatedPayment = {
$set: {
status: status,
},
};
const result = await paymentCollection.updateOne(filter, updatedPayment);
res.send(result);
});
app.delete("/payments/:id", verifyToken, verifyAdmin, async (req, res) => {
const id = req.params.id;
const query = { _id: new ObjectId(id) };
const result = await paymentCollection.deleteOne(query);
res.send(result);
});
app.post("/create-payment-intent", async (req, res) => {
const { price } = req.body;
const amount = parseInt(price * 100);
// console.log("Amoun in intent: " + amount);
// Create a PaymentIntent with the order amount and currency
const paymentIntent = await stripe.paymentIntents.create({
amount: amount,
currency: "usd",
payment_method_types: ["card"],
});
res.send({
clientSecret: paymentIntent.client_secret,
});
});
app.post("/payments", async (req, res) => {
const payment = req.body;
const paymentResult = await paymentCollection.insertOne(payment);
// Delete each item from the cart
// console.log("Payment Info:", payment);
const query = {
_id: {
$in: payment.cartIds.map((id) => new ObjectId(id)),
},
};
const deleteResult = await cartCollection.deleteMany(query);
// Send user email about payment confirmation
// mg.messages
// .create(process.env.MAIL_SENDING_DOMAIN, {
// from: "Excited User <[email protected]>",
// to: ["[email protected]"],
// subject: "Confirmation Of your Order - Bistro Boss",
// text: "Testing",
// html: `
// <div>
// <h2>Thank you for your Order</h2>
// <h4>Your Transaction ID is - <strong>${payment.transactionId}</strong></h4>
// <p>We would love to get your feedback about the food!</p>
// </div>
// `,
// })
// .then((msg) => console.log(msg)) // logs response data
// .catch((err) => console.error(err)); // logs any error
res.send({ paymentResult, deleteResult });
});
// Stats or Analytics: Aggregate pipelines
app.get("/admin-stats", verifyToken, verifyAdmin, async (req, res) => {
const users = await userCollection.estimatedDocumentCount();
const menuItems = await menuCollection.estimatedDocumentCount();
const orders = await paymentCollection.estimatedDocumentCount();
// Not a efficient way to calculate by loading all the data
// const payments = await paymentCollection.find().toArray();
// const revenue = payments.reduce((total, item) => total + item.price, 0);
const result = await paymentCollection
.aggregate([
{
$group: {
_id: null,
totalRevenue: {
$sum: "$price",
},
},
},
])
.toArray();
const revenue = result.length > 0 ? result[0].totalRevenue : 0;
res.send({ users, menuItems, orders, revenue });
});
app.get("/order-stats", verifyToken, verifyAdmin, async (req, res) => {
const result = await paymentCollection
.aggregate([
{
$unwind: "$menuItemIds",
},
{
$lookup: {
from: "menu",
let: { menuItemId: { $toObjectId: "$menuItemIds" } },
pipeline: [
{ $match: { $expr: { $eq: ["$_id", "$$menuItemId"] } } },
],
as: "menuItems",
},
},
{
$unwind: "$menuItems",
},
{
$group: {
_id: "$menuItems.category",
quantity: { $sum: 1 },
revenue: { $sum: "$menuItems.price" },
},
},
{
$project: {
_id: 0,
category: "$_id",
quantity: 1,
revenue: 1,
},
},
])
.toArray();
res.send(result);
});
app.get("/user-stats/:email", async (req, res) => {
const query = { email: req.params.email };
const userQuery = { user: req.params.email };
const orders = await paymentCollection.countDocuments(query);
const reviews = await reviewCollection.countDocuments(userQuery);
const bookings = await bookingCollection.countDocuments(query);
res.send({ orders, reviews, bookings });
});
// Message related api
app.get("/messages", async (req, res) => {
const result = await messageCollection.find().toArray();
res.send(result);
})
app.post("/messages", async (req, res) => {
const message = req.body;
const result = await messageCollection.insertOne(message);
res.send(result);
})
app.delete("/messages/:id", async (req, res) => {
const id = req.params.id;
const query = {_id: new ObjectId(id)};
const result = await messageCollection.deleteOne(query);
res.send(result);
});
// Send a ping to confirm a successful connection
// await client.db("admin").command({ ping: 1 });
// console.log(
// "Pinged your deployment. You successfully connected to MongoDB!"
// );
} finally {
// Ensures that the client will close when you finish/error
// await client.close();
}
}
run().catch(console.dir);
app.get("/", (req, res) => {
res.send("Bistro Boss server running...");
});
app.listen(port, () => {
console.log(`Listening on port ${port}...`);
});