-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
366 lines (329 loc) · 11.5 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
// Importing Required Modules
const express = require("express");
const app = express();
const cors = require("cors");
const jwt = require("jsonwebtoken");
require("dotenv").config();
// console.log("STRIPE_SECRET_KEY:", process.env.STRIPE_SECRET_KEY);
// Initialize Stripe
const stripe = require("stripe")(process.env.STRIPE_SECRET_KEY);
// Set the Port
const port = process.env.PORT || 5000;
//Middleware Setup
// MongoDB Setup
const corsOptions = {
origin: [
"http://localhost:5173",
"https://bistro-boss-f43fa.web.app",
"https://bistro-boss-server-opal-nu.vercel.app",
"bistro-boss-server-avksmllls-jayed-hossains-projects.vercel.app",
"https://bistro-boss-server-q6lizj4cv-jayed-hossains-projects.vercel.app",
], // Allow specific domains
methods: ["GET", "POST", "PUT", "PATCH", "DELETE"],
allowedHeaders: ["Content-Type", "Authorization"], // Allowed headers
credentials: true, // Allow credentials like cookies and tokens if needed
};
app.use(cors(corsOptions));
app.use(express.json());
// Connection string
const { MongoClient, ServerApiVersion, ObjectId } = require("mongodb");
const uri = `mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASS}@cluster0.4vti4xu.mongodb.net/?retryWrites=true&w=majority`;
// 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,
},
});
// Define Asynchronous Function to Connect to MongoDB
async function run() {
try {
// Connect the client to the server (optional starting in v4.7)
// await client.connect();
// Define Collections
const menuCollection = client.db("bistroDB").collection("menu");
const usersCollection = client.db("bistroDB").collection("users");
const reviewsCollection = client.db("bistroDB").collection("reviews");
const cartsCollection = client.db("bistroDB").collection("carts");
const paymentCollection = client.db("bistroDB").collection("payments");
// JWT Token Generation
// 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 });
});
// Middleware for Verifying Tokens
const verifyToken = (req, res, next) => {
// console.log("Inside verify token:", req.headers.authorization);
console.log("req.headers.authorization", 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();
});
};
// Middleware for Verifying Admin Role
const verifyAdmin = async (req, res, next) => {
const email = req.decoded.email;
const query = { email: email };
const user = await usersCollection.findOne(query);
const isAdmin = user?.role === "admin";
if (!isAdmin) {
return res.status(403).send({ message: "Forbidden access" });
}
next();
};
// User-Related API Endpoints
app.get("/users", verifyToken, verifyAdmin, async (req, res) => {
const result = await usersCollection.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 usersCollection.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 doesn't exists
// You can do this many ways(1. email unique, 2.upsert 3. simple checking)
const query = { email: user.email };
const existingUser = await usersCollection.findOne(query);
if (existingUser) {
return res.send({ message: "User already exists", insertedId: null });
}
const result = await usersCollection.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 updateDoc = {
$set: {
role: "admin",
},
};
const result = await usersCollection.updateOne(filter, updateDoc);
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 cartsCollection.deleteOne(query);
res.send(result);
});
// Menu-Related API Endpoints
app.get("/menu", async (req, res) => {
const result = await menuCollection.find().toArray();
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", async (req, res) => {
const item = req.body;
const id = req.params.id;
const filter = { _id: new ObjectId(id) };
const updateDoc = {
$set: {
name: item.name,
category: item.category,
price: item.price,
recipe: item.recipe,
image: item.image,
},
};
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);
});
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.get("/reviews", async (req, res) => {
const result = await reviewsCollection.find().toArray();
res.send(result);
});
//Carts collection
app.get("/carts", async (req, res) => {
const email = req.query.email;
const query = { email: email };
const result = await cartsCollection.find(query).toArray();
res.send(result);
});
app.post("/carts", async (req, res) => {
const cartItem = req.body;
const result = await cartsCollection.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 cartsCollection.deleteOne(query);
res.send(result);
});
// Payment intent
app.post("/create-payment-intent", async (req, res) => {
const { price } = req.body;
const amount = parseInt(price * 100);
// console.log(amount, " amount inside the intent.");
// 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.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.post("/payment", async (req, res) => {
const payment = req.body;
const paymentResult = await paymentCollection.insertOne(payment);
// Carefully 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 cartsCollection.deleteMany(query);
res.send({ paymentResult, deleteResult });
});
// Statistics (Stats) or analytics
app.get("/admin-stats", verifyToken, verifyAdmin, async (req, res) => {
const users = await usersCollection.estimatedDocumentCount();
const menuItems = await menuCollection.estimatedDocumentCount();
const orders = await paymentCollection.estimatedDocumentCount();
//This is not the best way
// const payments = await paymentCollection.find().toArray();
// const revenue = payments.reduce(
// (total, payment) => total + payment.price,
// 0
// );
const result = await paymentCollection
.aggregate([
{
$group: {
_id: null,
totalRevenue: {
$sum: "$price",
},
},
},
])
.toArray();
const revenue =
result.length > 0 ? result[0].totalRevenue.toFixed(2) : "0.00";
res.send({
users,
menuItems,
orders,
revenue,
});
});
// Using aggregate pipeline
/**
* ----------------------------
* NON-Efficient Way
* ------------------------------
* 1. load all the payments
* 2. for every menuItemIds (which is an array), go find the item from menu collection
* 3. for every item in the menu collection that you found from a payment entry (document)
*/
// Using aggregate pipeline
app.get("/order-stats", verifyToken, verifyAdmin, async (req, res) => {
const result = await paymentCollection
.aggregate([
{
$unwind: "$menuItemIds",
},
{
$lookup: {
from: "menu",
localField: "menuItemIds",
foreignField: "_id",
as: "menuItems",
},
},
// Since $lookup results in an array (even if it's just one matched item), we need to "unwind" the array so that we can work with individual documents.
{
$unwind: "$menuItems",
},
{
$group: {
_id: "$menuItems.category",
quantity: { $sum: 1 },
revenue: { $sum: "$menuItems.price" },
},
},
{
$project: {
_id: 0,
category: "$_id",
quantity: "$quantity",
revenue: "$revenue",
},
},
])
.toArray(); // It converts a MongoDB cursor (which is the result of a query) into an array of documents.
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(); // avoiding error - Client must be connected before running operations
}
}
run().catch(console.dir);
app.get("/", (req, res) => {
res.send("Boss is sitting.");
});
app.listen(port, () => {
console.log(`Bistro boss is sitting on port ${port}`);
});