-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
477 lines (369 loc) · 14.8 KB
/
index.js
File metadata and controls
477 lines (369 loc) · 14.8 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
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
const express = require('express');
const cors = require('cors');
const { MongoClient, ServerApiVersion, ObjectId } = require('mongodb');
const jwt = require('jsonwebtoken');
const cookieParser = require('cookie-parser');
require('dotenv').config()
const app = express();
const port = process.env.PORT || 5000;
// miidleware written here http://localhost:5173
const corsConfig = {
origin: [
'http://localhost:5173',
'https://product-pulse-7aeac.web.app',
'https://product-pulse-7aeac.firebaseapp.com'
],
credentials: true,
optionSuccessStatus: 200,
methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE']
}
app.use(cors(corsConfig))
app.use(express.json());
app.use(cookieParser());
const logger = async (req, res, next) => {
console.log('called:', req.host, req.originalUrl)
next();
}
const verifyToken = async (req, res, next) => {
const token = req?.cookies?.token;
console.log('value of token in middleware', token)
if (!token) {
return res.status(401).send({ message: 'unauthorized access' })
}
jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, decoded) => {
//error
if (err) {
console.log(err);
return res.status(401).send({ message: 'unauthorized access' })
}
//if token is valid then it would be docoded
console.log('value in the token', decoded)
req.decoded = decoded;
// req.user = decoded
next()
})
}
const uri = `mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASSWORD}@cluster0.5ynzghe.mongodb.net/?retryWrites=true&w=majority&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,
}
});
const cookieOption = {
httpOnly: true,
semeSite: process.env.NODE_ENV === 'production' ? 'none' : 'strict',
secure: process.env.NODE_ENV === 'production' ? true : false,
}
async function run() {
try {
const queryCollection = client.db('productPulseDB').collection('queries');
const recommendationCollection = client.db('productPulseDB').collection('recommendations');
const userCollection = client.db('productPulseDB').collection('users');
// const categoryCollection = client.db('craftifycreationsDB').collection('category');
//auth related api create token
app.post('/jwt', logger, async (req, res) => {
const user = req.body;
console.log(user);
const token = jwt.sign(user, process.env.ACCESS_TOKEN_SECRET,
{ expiresIn: '1d' })
res
.cookie('token', token, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: process.env.NODE_ENV === 'production' ? 'none' : 'strict',
})
.send({ success: true });
})
//clear token
app.post('/logout', async (req, res) => {
const user = req.body;
console.log('logging out ', user);
res.clearCookie('token', { ...cookieOption, maxAge: 0 }).send({ success: true });
})
// use verify admin 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/admin/:email', verifyToken, async (req, res) => {
const email = req.params.email;
if (email !== req.decoded.email) {
return res.status(403).send({ message: 'unauthorized access' })
}
const query = { email: email }
const user = await userCollection.findOne(query);
let admin = false;
if (user) {
admin = user.role === 'admin';
}
res.send({ admin });
})
//users api
app.get('/users',verifyToken, verifyAdmin, async (req, res) => {
const result = await userCollection.find().toArray();
res.send(result);
})
app.post('/users', async (req, res) => {
const user = req.body;
const query = { email: user.email }
const existingUser = await userCollection.findOne(query)
if (existingUser) {
return res.send({ message: 'user already exist', insertedId: null })
}
const result = await userCollection.insertOne(user);
res.send(result);
})
app.patch('/users/admin/:id', 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', async (req, res) => {
const id = req.params.id;
const query = { _id: new ObjectId(id) };
const result = await userCollection.deleteOne(query);
res.send(result);;
})
//query collect
app.get('/query', logger, async (req, res) => {
const cursor = queryCollection.find();
const result = await cursor.toArray();
res.send(result);
})
app.get('/recommendation', logger, verifyToken, async (req, res) => {
const cursor = recommendationCollection.find();
const result = await cursor.toArray();
res.send(result);
})
//query with
// Get a single query data from db using id
app.get('/query/:id', async (req, res) => {
const id = req.params.id;
// const querys = { _id: (id) }
query = { $or: [{ _id: new ObjectId(id) }, { _id: id }] };
const result = await queryCollection.findOne(query)
res.send(result)
})
// Get a single query data from db using id
app.get('/recommendation/:id', async (req, res) => {
const id = req.params.id;
let query;
// Check if the id is a valid ObjectId
query = { $or: [{ queries_id: new ObjectId(id) }, { queries_id: id }] };
try {
const results = await recommendationCollection.find(query).toArray();
if (results.length > 0) {
res.send(results);
} else {
res.status(404).send("No recommendations found for the specified id");
}
} catch (error) {
console.error("Error:", error);
res.status(500).send("Internal Server Error");
}
});
// Endpoint to search data based on user email
app.get('/query/email/:useremail',logger, verifyToken, async (req, res) => {
try {
// Extract the user email from the request parameters
const userEmail = req.params.useremail;
const tokenEmail = req.user.email;
console.log('token match',userEmail,tokenEmail)
// Check if the user associated with the token is the same as the requested user
if (userEmail !== tokenEmail) {
return res.status(403).json({ error: 'Forbidden access' });
}
// Search for data in the query collection based on the user email
const result = await queryCollection.find({ useremail: userEmail }).toArray();
// Send the search result back to the client
res.send(result);
} catch (error) {
// If an error occurs, send an error response
console.error('Error searching data by email:', error);
res.status(500).json({ error: 'Internal server error' });
}
});
app.get('/recommendation/email/:recommenderEmail',logger, verifyToken, async (req, res) => {
try {
// Extract the user email from the request parameters
const userEmail = req.params.recommenderEmail;
const tokenEmail = req.user.email;
console.log('token match',userEmail,tokenEmail)
// Check if the user associated with the token is the same as the requested user
if (userEmail !== tokenEmail) {
return res.status(403).json({ error: 'Forbidden access' });
}
// Search for data in the query collection based on the user email
const result = await recommendationCollection.find({ recommenderEmail: userEmail }).toArray();
// Send the search result back to the client
res.send(result);
} catch (error) {
// If an error occurs, send an error response
console.error('Error searching data by email:', error);
res.status(500).json({ error: 'Internal server error' });
}
});
// recommendation search based on user email
app.get('/recommendations/email/:QueryEmail',logger,verifyToken, async (req, res) => {
try {
// Extract the user email from the request parameters
const userEmail = req.params.QueryEmail;
const tokenEmail = req.user.email;
console.log('token match',userEmail,tokenEmail)
// Check if the user associated with the token is the same as the requested user
if (userEmail !== tokenEmail) {
return res.status(403).json({ error: 'Forbidden access' });
}
// Search for data in the query collection based on the user email
const result = await recommendationCollection.find({ QueryEmail: userEmail }).toArray();
// Send the search result back to the client
res.send(result);
} catch (error) {
// If an error occurs, send an error response
console.error('Error searching data by email:', error);
res.status(500).json({ error: 'Internal server error' });
}
});
// delete query
app.delete('/query/:id', async (req, res) => {
const id = req.params.id;
const query = { $or: [{ _id: new ObjectId(id) }, { _id: id }] };
try {
const result = await queryCollection.deleteOne(query);
if (result.deletedCount === 1) {
res.status(200).json({ success: true, message: "Query deleted successfully." });
} else {
res.status(404).json({ success: false, message: "Query not found." });
}
} catch (error) {
console.error("Error deleting query:", error);
res.status(500).json({ success: false, message: "Failed to delete the query." });
}
});
//delete recommendation
app.delete('/recommendation/:id', async (req, res) => {
const id = req.params.id;
const query = { $or: [{ _id: new ObjectId(id) }, { _id: id }] };
try {
// Get the recommendationData first
const recommendationData = await recommendationCollection.findOne(query);
if (!recommendationData) {
return res.status(404).json({ success: false, message: "Recommendation not found." });
}
const result = await recommendationCollection.deleteOne(query);
if (result.deletedCount === 1) {
// Update the recommendation count for the corresponding query
await queryCollection.updateOne(
// { _id: new ObjectId(recommendationData.queries_id) },
{ $or: [{ _id: new ObjectId(recommendationData.queries_id) }, { _id: recommendationData.queries_id }] },
{ $inc: { recommendationcount: -1 } } // Decrease count by 1
);
res.status(200).json({ success: true, message: "Recommendation deleted successfully." });
} else {
res.status(404).json({ success: false, message: "Recommendation not found." });
}
} catch (error) {
console.error("Error deleting recommendation:", error);
res.status(500).json({ success: false, message: "Failed to delete the recommendation." });
}
});
//update query
app.put('/updateQuery/:id', async (req, res) => {
const id = req.params.id;
const query = { $or: [{ _id: new ObjectId(id) }, { _id: id }] };
const updatedQuery = req.body;
const updateQueries = {
$set: {
productname: updatedQuery.productname,
productbrand: updatedQuery.productbrand,
productimageurl: updatedQuery.productimageurl,
querytitle: updatedQuery.querytitle,
boycottingreasondetails: updatedQuery.boycottingreasondetails
}
};
try {
const result = await queryCollection.updateOne(query, updateQueries);
if (result.modifiedCount > 0) {
res.status(200).json({ success: true, message: "Query updated successfully." });
} else {
res.status(404).json({ success: false, message: "Query not found." });
}
} catch (error) {
console.error("Error updating query:", error);
res.status(500).json({ success: false, message: "Failed to update the query." });
}
});
// Save a recommend data in db
app.post('/recommendation', async (req, res) => {
try {
const recommendationData = req.body;
// Save the recommendation data to the recommendations collection
await recommendationCollection.insertOne(recommendationData);
// Update the recommendation count for the corresponding query
// await queryCollection.updateOne(
// { _id: new ObjectId(recommendationData.queries_id) },
// { $inc: { recommendationcount: 1 } }
// );
// Update the recommendation count for the corresponding query
await queryCollection.updateOne(
{ $or: [{ _id: new ObjectId(recommendationData.queries_id) }, { _id: recommendationData.queries_id }] },
{ $inc: { recommendationcount: 1 } }
);
res.status(201).json({ message: 'Recommendation added successfully' });
} catch (error) {
console.error('Error adding recommendation:', error);
res.status(500).json({ error: 'Internal server error' });
}
});
// app.post('/recommendation', async (req, res) => {
// const recommendationData = req.body
// const result = await recommendationCollection.insertOne(recommendationData)
// res.send(result)
// })
// Save a query data in db
app.post('/query', async (req, res) => {
const queryData = req.body
const result = await queryCollection.insertOne(queryData)
res.send(result)
})
//stats or analytics
app.get('/user-stats', async(req,res)=>{
const users = await userCollection.estimatedDocumentCount();
const query = await queryCollection.estimatedDocumentCount();
const recommendation = await recommendationCollection.estimatedDocumentCount();
res.send({
users,
query,
recommendation,
})
})
// 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('product-pulse-server server is running ')
})
app.listen(port, () => {
console.log(`product-pulse is running on port: ${port}`)
})