-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
448 lines (363 loc) · 14.8 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
const express = require('express');
const cors = require('cors');
const { MongoClient, ServerApiVersion, ObjectId } = require('mongodb');
const jwt = require('jsonwebtoken');
require('dotenv').config();
const app = express();
const port = process.env.PORT || 5000;
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);
// middleware
app.use(cors());
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Methods', 'DELETE, PUT, GET, POST');
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.use(express.json());
const uri = `mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASS}@cluster0.anvyz.mongodb.net/?retryWrites=true&w=majority`;
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true, serverApi: ServerApiVersion.v1 });
function verifyJWT(req, res, next) {
const authHeader = req.headers.authorization;
// console.log('auth header hellooo', authHeader);
if (!authHeader) {
return res.status(401).send({ message: 'Unauthorized access' });
}
const token = authHeader.split(' ')[1];
// console.log('hello token', token)
jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, function (err, decoded) {
if (err) {
return res.status(403).send({ message: 'Forbidden access' })
}
req.decoded = decoded;
next();
})
}
async function run() {
try {
await client.connect();
const productCollection = client.db('little-leaf').collection('products');
const cartCollection = client.db('little-leaf').collection('carts');
const userCollection = client.db('little-leaf').collection('users');
const orderCollection = client.db('little-leaf').collection('orders');
const blogCollection = client.db('little-leaf').collection('blogs');
const reviewCollection = client.db('little-leaf').collection('reviews');
const orderItemsCollection = client.db('little-leaf').collection('orderItems');
//middleware
const verifyAdmin = async (req, res, next) => {
const requester = req.decoded.email;
const requesterAccount = await userCollection.findOne({ email: requester });
if (requesterAccount.role === 'admin') {
next();
}
else {
res.status(403).send({ message: 'forbidden' });
}
}
app.post("/create-payment-intent", async (req, res) => {
const service = req.body;
const price = service.price;
//convert to poysha
const amount = price * 100;
const paymentIntent = await stripe.paymentIntents.create({
amount: amount,
currency: "usd",
payment_method_types: ['card']
});
res.send({ clientSecret: paymentIntent.client_secret })
})
//find all admin
app.get('/admin/:email', async (req, res) => {
const email = req.params.email;
const user = await userCollection.findOne({ email: email });
const isAdmin = user?.role === 'admin';
res.send({ admin: isAdmin })
})
// // get admin
// app.get('/user/:email', async (req, res) => {
// const email = req.params.email;
// console.log('got this email', email)
// const user = await userCollection.findOne({ email: email });
// const isAdmin = user.role === 'admin';
// res.send({ admin: isAdmin })
// })
// put user by email endpoint
app.put('/users/:email', async (req, res) => {
const email = req.params.email;
// console.log('got this email', email)
const user = req.body;
// console.log('got this user', user)
const filter = { email: email };
const options = { upsert: true };
const updateDoc = {
$set: user,
};
const result = await userCollection.updateOne(filter, updateDoc, options);
const token = jwt.sign({ email: email }, process.env.ACCESS_TOKEN_SECRET, { expiresIn: '2d' });
res.send({ result, token });
})
//make an user admin and check admin
app.put('/users/admin/:email', verifyJWT, verifyAdmin, async (req, res) => {
const email = req.params.email;
const filter = { email: email };
const updateDoc = {
// paid: true,
// transactionId: payment.transectionId,
$set: { role: 'admin' }
};
const result = await userCollection.updateOne(filter, updateDoc);
res.send(result)
})
// get all users
app.get('/users', verifyJWT, verifyAdmin, async (req, res) => {
const users = await userCollection.find().toArray();
res.send(users);
})
// get api for products
// app.get('/product', async (req, res) => {
// console.log('query', req.query)
// const query = {};
// const cursor = productCollection.find(query);
// const products = await cursor.toArray();
// res.send(products);
// });
// get api for products
app.get('/product', async (req, res) => {
// console.log('query', req.query)
const page = parseInt(req.query.page);
const size = parseInt(req.query.size);
const query = {};
const cursor = productCollection.find(query);
let products
if (page || size) {
products = await cursor.skip(page * size).limit(size).toArray();
}
else {
products = await cursor.toArray();
}
res.send(products);
});
//for page count
app.get('/productCount', async (req, res) => {
const count = await productCollection.estimatedDocumentCount();
res.send({ count });
});
// get api with id for product
app.get('/product/:id', async (req, res) => {
const id = req.params.id;
const query = { _id: ObjectId(id) };
const product = await productCollection.findOne(query);
res.send(product);
})
// post api for cart //http://localhost:5000/cart
app.post('/cart', async (req, res) => {
const cart = req.body;
const result = await cartCollection.insertOne(cart);
res.send(result);
})
//Admin Works add new product
app.post('/product', verifyJWT, verifyAdmin, async (req, res) => {
const product = req.body;
// console.log(product)
const result = await productCollection.insertOne(product);
res.send(result);
})
//cancel or delete products from manage product
//http://localhost:5000/product/:id
app.delete('/product/:id', async (req, res) => {
const id = req.params.id;
const query = { _id: ObjectId(id) };
const result = await productCollection.deleteOne(query);
res.send(result);
})
//update products from manage product
//http://localhost:5000/product/:id
app.patch('/product/:id', async (req, res) => {
const id = req.params.id;
const updatedProduct = req.body;
// console.log(updatedProduct)
const filter = { _id: ObjectId(id) };
const options = { upsert: true };
const updateDoc = {
$set: {
plantName: updatedProduct.plantName,
price: updatedProduct.price,
inStock: updatedProduct.inStock,
description: updatedProduct.description,
imageUrl: updatedProduct.imageUrl,
imageAlt: updatedProduct.imageAlt,
categories: updatedProduct.categories,
},
};
const result = await productCollection.updateOne(filter, updateDoc, options);
res.send(result)
})
//for update quantity in cart //http://localhost:5000/carts/:id
app.patch('/carts/:id', async (req, res) => {
const id = req.params.id;
const cart = req.body
// console.log(cart)
const filter = { _id: ObjectId(id) };
const updateDoc = {
$set: {
quantity: cart.quantity,
}
};
const updatedOrder = await cartCollection.updateOne(filter, updateDoc)
res.send(updateDoc)
})
// get api for carts
app.get('/carts/:email', async (req, res) => {
const email = req.params.email;
// console.log(email)
const filter = { email: email };
const cursor = cartCollection.find(filter);
const carts = await cursor.toArray();
res.send(carts);
})
//cancel or delete cart order
//http://localhost:5000/carts/:id
app.delete('/carts/:id', async (req, res) => {
const id = req.params.id;
const query = { _id: ObjectId(id) };
const result = await cartCollection.deleteOne(query);
res.send(result);
})
///for stripe test
app.get('/cart/:id', async (req, res) => {
const id = req.params.id;
const query = { _id: ObjectId(id) };
const order = await cartCollection.findOne(query);
res.send(order);
})
// remove carts
app.delete('/carts', async (req, res) => {
const result = await cartCollection.remove({});
res.send(result);
})
// get all orders from manageorders
// app.get('/orders', async (req, res) => {
// const users = await orderCollection.find().toArray();
// res.send(users);
// })
app.get('/orders', async (req, res) => {
const page = parseInt(req.query.page);
const size = parseInt(req.query.size);
const query = {};
const cursor = orderCollection.find(query);
let orders
if (page || size) {
orders = await cursor.skip(page * size).limit(size).toArray();
}
else {
orders = await cursor.toArray();
}
res.send(orders);
// const users = await orderCollection.find().toArray();
// res.send(users);
})
//order collection page count
app.get('/productCountOrder', async (req, res) => {
const count = await orderCollection.estimatedDocumentCount();
res.send({ count });
});
// post paid orders from checkout form
app.post('/orders', async (req, res) => {
const order = req.body;
const result = await orderCollection.insertOne(order);
res.send(result);
})
// post paid orders items from checkout form
app.post('/orderItem', async (req, res) => {
const order = req.body;
const result = await orderItemsCollection.insertOne(order);
res.send(result);
})
// manage order shipped property
app.put('/manageorder/:id', async (req, res) => {
const id = req.params.id;
const order = req.body;
const filter = { _id: ObjectId(id) };
const options = { upsert: true };
const updateDoc = {
$set: { pendingChange: 'shipped' }
};
const result = await orderCollection.updateOne(filter, updateDoc, options);
res.send(result)
})
// After successful payment instock updation
app.patch('/products/:id', async (req, res) => {
const id = req.params.id;
const product = req.body
// console.log(cart)
const filter = { _id: ObjectId(id) };
const updateDoc = {
$set: {
inStock: product.inStock,
}
};
const updatedOrder = await productCollection.updateOne(filter, updateDoc)
res.send(updateDoc)
})
// get api my orders with email for user
app.get('/myorders/:email', async (req, res) => {
const email = req.params.email;
// console.log(email)
const filter = { userEmail: email };
const orders = await orderCollection.find(filter).toArray();
res.send(orders);
})
// get api my orders with email for user
app.get('/myorderitems/:transectionId', async (req, res) => {
const reqTransectionId = req.params.transectionId;
// console.log(email)
const filter = { transectionId: reqTransectionId };
const orderItem = await orderItemsCollection.find(filter).toArray();
res.send(orderItem);
})
// add new blog by admin
app.post('/blogs', verifyJWT, verifyAdmin, async (req, res) => {
const blogs = req.body;
// console.log(blog)
const result = await blogCollection.insertOne(blogs);
res.send(result);
})
// get all blog by admin
app.get('/blogs', async (req, res) => {
const blogs = await blogCollection.find().toArray();
res.send(blogs);
})
// get api with id for blog
app.get('/blog/:id', async (req, res) => {
const id = req.params.id;
const query = { _id: ObjectId(id) };
const blog = await blogCollection.findOne(query);
res.send(blog);
})
// add review by user for every product
app.post('/reviews', async (req, res) => {
const reviews = req.body;
const result = await reviewCollection.insertOne(reviews);
res.send(result);
})
// get all reviews by user for every product
app.get('/review', async (req, res) => {
// const reqId = req.params.reviewId;
// console.log(reqId)
// const filter = { productId: reqId };
// const reviews = await reviewCollection.find(filter).toArray();
// res.send(reviews);
const reviews = await reviewCollection.find().toArray();
res.send(reviews);
})
}
finally {
}
}
run().catch(console.dir);
app.get('/', (req, res) => {
res.send('Hello from Little Leaf!');
})
app.listen(port, () => {
console.log(`Little Leaf listening on port ${port}`)
})