-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
406 lines (332 loc) · 11.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
// const express = require("express");
// const cors = require("cors");
// require('dotenv').config();
// const { MongoClient, ServerApiVersion, ObjectId } = require('mongodb');
// const app = express();
// const port = process.env.PORT || 9000;
// //Must remove "/" from your production URL
// app.use(
// cors({
// origin: [
// "http://localhost:5173",
// "https://assignment-11-volunteer.web.app",
// "https://assignment-11-volunteer.firebaseapp.com",
// ],
// credentials: true,
// })
// );
// app.use(cors());
// app.use(express.json());
// const uri = `mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASS}@atlascluster.yh51je0.mongodb.net/?retryWrites=true&w=majority&appName=AtlasCluster`;
// // console.log(uri);
// const client = new MongoClient(uri, {
// serverApi: {
// version: ServerApiVersion.v1,
// strict: true,
// deprecationErrors: true,
// }
// });
// async function run() {
// try {
// const needpostCollection = client.db('servesyncDB').collection('needpost');
// const reqsCollection = client.db('servesyncDB').collection('reqs');
// app.get('/needpost', async (req, res) => {
// const result = await needpostCollection.find().sort({ deadline: 1 }).toArray();
// res.send(result);
// });
// app.get('/needposts/:id', async (req, res) => {
// const id = req.params.id;
// const query = { _id: new ObjectId(id) };
// const result = await needpostCollection.findOne(query);
// res.send(result);
// });
// app.post('/add', async (req, res) => {
// const addData = req.body;
// const result = await needpostCollection.insertOne(addData);
// res.send(result);
// });
// app.get("/mypost/:email", async (req, res) => {
// const email = req.params.email
// const query = {'organizer.email' : email}
// const result = await needpostCollection.find(query).toArray();
// res.send(result);
// });
// app.delete("/post/:id", async (req, res) => {
// const id = req.params.id
// const query = {_id : new ObjectId(id)}
// const result = await needpostCollection.deleteOne(query);
// res.send(result);
// });
// app.put("/post/:id", async (req, res) => {
// try {
// const id = req.params.id;
// const postData = req.body;
// const query = { _id: new ObjectId(id) };
// const options = { upsert: true };
// const updateDoc = {
// $set: {
// ...postData
// }
// };
// const result = await needpostCollection.updateOne(query, updateDoc, options);
// res.send(result);
// } catch (error) {
// console.error("Error updating post:", error);
// res.status(500).send({ error: "An error occurred while updating the post" });
// }
// });
// app.get("/myreq/:email", async (req, res) => {
// const email = req.params.email
// const query = {email}
// const result = await reqsCollection.find(query).toArray();
// res.send(result);
// });
// app.get("/postreq/:email", async (req, res) => {
// const email = req.params.email
// const query = {'organizer.email' : email}
// const result = await reqsCollection.find(query).toArray();
// res.send(result);
// });
// app.patch("/updatereq/:id", async (req, res) => {
// try {
// const id = req.params.id;
// const status = req.body;
// const query = { _id: new ObjectId(id) };
// const updateDoc = {
// $set: status,
// };
// const result = await reqsCollection.updateOne(query, updateDoc);
// res.send(result);
// } catch (error) {
// console.error("Error updating post:", error);
// res.status(500).send({ error: "An error occurred while updating the post" });
// }
// });
// app.delete("/postreq/:id", async (req, res) => {
// const id = req.params.id;
// const query = { _id: new ObjectId(id) };
// try {
// const result = await reqsCollection.deleteOne(query);
// if (result.deletedCount === 1) {
// res.send({ message: "Request deleted successfully" });
// } else {
// res.status(404).send({ error: "Request not found" });
// }
// } catch (error) {
// console.error("Error deleting request:", error);
// res.status(500).send({ error: "An error occurred while deleting the request" });
// }
// });
// app.post('/req', async (req, res) => {
// try {
// const reqData = req.body;
// const postId = reqData.postId;
// const result = await reqsCollection.insertOne(reqData);
// const updateDoc = {
// $set: {
// volunteers_needed: parseInt(reqData.volunteers_needed)
// }
// };
// const query = { _id: new ObjectId(reqData.postId) };
// await needpostCollection.updateOne(query, updateDoc);
// const updatePostDoc = await needpostCollection.updateOne(query, { $inc: { volunteers_needed: -1 } });
// res.send(result);
// } catch (error) {
// console.error('Error:', error);
// res.status(500).json({ message: 'An error occurred while processing your request' });
// }
// });
// // 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 {
// }
// }
// run().catch(console.dir);
// app.get("/", (req, res) => {
// res.send("server is running");
// });
// app.listen(port, () => {
// console.log(`server is running on port: ${port}`);
// });
const express = require("express");
const cors = require("cors");
require('dotenv').config();
const { MongoClient, ServerApiVersion, ObjectId } = require('mongodb');
const jwt = require('jsonwebtoken');
const app = express();
const port = process.env.PORT || 9000;
// CORS setup
app.use(
cors({
origin: [
"http://localhost:5173",
"https://assignment-11-volunteer.web.app",
"https://assignment-11-volunteer.firebaseapp.com",
],
credentials: true,
})
);
// Express middleware setup
app.use(cors());
app.use(express.json());
// MongoDB connection setup
const uri = `mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASS}@atlascluster.yh51je0.mongodb.net/?retryWrites=true&w=majority`;
const client = new MongoClient(uri, {
serverApi: {
version: ServerApiVersion.v1,
strict: true,
deprecationErrors: true,
}
});
// Main server logic
async function run() {
try {
// Connect to MongoDB
await client.connect();
const needpostCollection = client.db('servesyncDB').collection('needpost');
const reqsCollection = client.db('servesyncDB').collection('reqs');
// Routes
// Get all need posts
app.get('/needpost', async (req, res) => {
const result = await needpostCollection.find().sort({ deadline: 1 }).toArray();
res.send(result);
});
app.post('/jwt',async (req,res) =>{
const user = req.body;
console.log('token',user);
const token = jwt.sign(user, process.env.ACCESS_TOKEN_SECRET, {
expiresIn:'365d'
})
res.cookie('token', token, {
httpOnly:true,
secure: true,
sameSite: "strict",
})
res.send({ success : true })
})
// app.use('/private', (req, res, next) => {
// const token = req.headers.authorization?.split(' ')[1];
// if (!token) return res.status(401).json({ message: 'Authentication failed' });
// jwt.verify(token, process.env.JWT_SECRET, (err, decodedToken) => {
// if (err) return res.status(403).json({ message: 'Forbidden' });
// req.userData = decodedToken;
// next();
// });
// });
// Your other routes go here...
app.get('/needposts/:id', async (req, res) => {
const id = req.params.id;
const query = { _id: new ObjectId(id) };
const result = await needpostCollection.findOne(query);
res.send(result);
});
app.post('/add', async (req, res) => {
const addData = req.body;
const result = await needpostCollection.insertOne(addData);
res.send(result);
});
app.get("/mypost/:email", async (req, res) => {
const email = req.params.email
const query = {'organizer.email' : email}
const result = await needpostCollection.find(query).toArray();
res.send(result);
});
app.delete("/post/:id", async (req, res) => {
const id = req.params.id
const query = {_id : new ObjectId(id)}
const result = await needpostCollection.deleteOne(query);
res.send(result);
});
app.put("/post/:id", async (req, res) => {
try {
const id = req.params.id;
const postData = req.body;
const query = { _id: new ObjectId(id) };
const options = { upsert: true };
const updateDoc = {
$set: {
...postData
}
};
const result = await needpostCollection.updateOne(query, updateDoc, options);
res.send(result);
} catch (error) {
console.error("Error updating post:", error);
res.status(500).send({ error: "An error occurred while updating the post" });
}
});
app.get("/myreq/:email", async (req, res) => {
const email = req.params.email
const query = {email}
const result = await reqsCollection.find(query).toArray();
res.send(result);
});
app.get("/postreq/:email", async (req, res) => {
const email = req.params.email
const query = {'organizer.email' : email}
const result = await reqsCollection.find(query).toArray();
res.send(result);
});
app.patch("/updatereq/:id", async (req, res) => {
try {
const id = req.params.id;
const status = req.body;
const query = { _id: new ObjectId(id) };
const updateDoc = {
$set: status,
};
const result = await reqsCollection.updateOne(query, updateDoc);
res.send(result);
} catch (error) {
console.error("Error updating post:", error);
res.status(500).send({ error: "An error occurred while updating the post" });
}
});
app.delete("/postreq/:id", async (req, res) => {
const id = req.params.id;
const query = { _id: new ObjectId(id) };
try {
const result = await reqsCollection.deleteOne(query);
if (result.deletedCount === 1) {
res.send({ message: "Request deleted successfully" });
} else {
res.status(404).send({ error: "Request not found" });
}
} catch (error) {
console.error("Error deleting request:", error);
res.status(500).send({ error: "An error occurred while deleting the request" });
}
});
app.post('/req', async (req, res) => {
try {
const reqData = req.body;
const postId = reqData.postId;
const result = await reqsCollection.insertOne(reqData);
const updateDoc = {
$set: {
volunteers_needed: parseInt(reqData.volunteers_needed)
}
};
const query = { _id: new ObjectId(reqData.postId) };
await needpostCollection.updateOne(query, updateDoc);
const updatePostDoc = await needpostCollection.updateOne(query, { $inc: { volunteers_needed: -1 } });
res.send(result);
} catch (error) {
console.error('Error:', error);
res.status(500).json({ message: 'An error occurred while processing your request' });
}
});
// Ping route
app.get("/", (req, res) => {
res.send("Server is running");
});
// Start the server
app.listen(port, () => {
console.log(`Server is running on port: ${port}`);
});
} catch (error) {
console.error('Error:', error);
}
}
run().catch(console.dir);