-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
248 lines (211 loc) · 8.71 KB
/
index.js
File metadata and controls
248 lines (211 loc) · 8.71 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
const express = require('express');
const cors = require('cors');
const jwt = require('jsonwebtoken');
const cookieParser = require('cookie-parser');
const { MongoClient, ServerApiVersion, ObjectId } = require('mongodb');
require('dotenv').config();
const port = process.env.PORT || 5000;
const app = express();
const corsOptions = {
origin: ['http://localhost:5173', 'https://tasksphere-d188b.web.app'],
credentials: true,
optionSuccessStatus: 200,
}
//middleware
app.use(cors(corsOptions));
app.use(express.json());
app.use(cookieParser());
//Verify jwt middleware
const verifyToken = (req, res, next) => {
const token = req.cookies?.token;
if (!token) return res.status(401).send({ message: 'unauthorized access' });
if (token) {
jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, decoded) => {
if (err) {
console.log(err);
return res.status(401).send({ message: 'unauthorized access' });
}
// console.log(decoded);
req.user = decoded;
next();
})
}
}
// const uri = `mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASS}@cluster0.qtkz8.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0`;
var uri = `mongodb://${process.env.DB_USER}:${process.env.DB_PASS}@cluster0-shard-00-00.qtkz8.mongodb.net:27017,cluster0-shard-00-01.qtkz8.mongodb.net:27017,cluster0-shard-00-02.qtkz8.mongodb.net:27017/?ssl=true&replicaSet=atlas-64o5c2-shard-0&authSource=admin&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,
}
});
async function run() {
try {
// Connect the client to the server (optional starting in v4.7)
// await client.connect();
const jobsCollection = client.db('taskSphere').collection('jobs');
const bidsCollection = client.db('taskSphere').collection('bids');
//JWT generate
app.post('/jwt', async (req, res) => {
const email = req.body;
const token = jwt.sign(email, process.env.ACCESS_TOKEN_SECRET, { expiresIn: '365d' })
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 on logout
app.get('/logout', async (req, res) => {
res.clearCookie('token', {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: process.env.NODE_ENV === 'production' ? 'none' : 'strict',
maxAge: 0,
}).send({ success: true })
})
//Get all jobs data from db
app.get('/jobs', async (req, res) => {
const result = await jobsCollection.find().toArray();
res.send(result);
})
//Get a single job data from database using job id
app.get('/job/:id', async (req, res) => {
const id = req.params.id;
const query = { _id: new ObjectId(id) };
const result = await jobsCollection.findOne(query);
res.send(result);
})
//Save a bid data in database
app.post('/bid', async (req, res) => {
const bidData = req.body;
// console.log(bidData);
//Check if its a duplicate request
const query = {
email: bidData.email,
jobId: bidData.jobId,
}
const alreadyApplied = await bidsCollection.findOne(query);
// console.log(alreadyApplied);
if (alreadyApplied) {
return res
.status(400)
.send('You have already placed a bid on this job.');
}
const result = await bidsCollection.insertOne(bidData);
// Update bid count in jobs collection
const updateDoc = {
$inc: { bid_count: 1 },
}
const jobQuery = { _id: new ObjectId(bidData.jobId) }
const updateBidCount = await jobsCollection.updateOne(jobQuery, updateDoc)
// console.log(updateBidCount)
res.send(result);
})
//Save a job data in database
app.post('/job', async (req, res) => {
const jobData = req.body;
const result = await jobsCollection.insertOne(jobData);
res.send(result);
})
//Get all jobs posted by a specific user
app.get('/jobs/:email', verifyToken, async (req, res) => {
const tokenEmail = req.user.email;
const email = req.params.email;
if (tokenEmail !== email) {
return res.status(403).send({ message: 'forbidden access' });
}
const query = { 'buyer.email': email };
const result = await jobsCollection.find(query).toArray();
res.send(result);
})
//Delete a job data from database
app.delete('/job/:id', async (req, res) => {
const id = req.params.id;
const query = { _id: new ObjectId(id) };
const result = await jobsCollection.deleteOne(query);
res.send(result);
})
//Update a job in database
app.put('/job/:id', verifyToken, async (req, res) => {
const id = req.params.id;
const jobData = req.body;
const query = { _id: new ObjectId(id) };
const options = { upsert: true };
const updateDoc = {
$set: {
...jobData,
},
}
const result = await jobsCollection.updateOne(query, updateDoc, options);
res.send(result);
})
//Get all bids for a user by email from db
app.get('/my-bids/:email', verifyToken, async (req, res) => {
const email = req.params.email;
const query = { email };
const result = await bidsCollection.find(query).toArray();
res.send(result);
})
//Get all bid requests from db for job owner
app.get('/bid-requests/:email', verifyToken, async (req, res) => {
const email = req.params.email;
const query = { 'buyer.email': email };
// console.log(query);
const result = await bidsCollection.find(query).toArray();
res.send(result);
})
//Update bid status
app.patch('/bid/:id', async (req, res) => {
const id = req.params.id;
const status = req.body;
const query = { _id: new ObjectId(id) };
const updateDoc = {
$set: status,
}
const result = await bidsCollection.updateOne(query, updateDoc);
res.send(result);
})
//Get all jobs data from db for pagination
app.get('/all-jobs', async (req, res) => {
const size = parseInt(req.query.size);
const page = parseInt(req.query.page) - 1;
const filter = req.query.filter;
const sort = req.query.sort;
const search = req.query.search;
// console.log(size, page);
let query = {
job_title: { $regex: search, $options: 'i' },
};
if (filter) query.category = filter;
let options = {}
if (sort) options = { sort: { deadline: sort === 'asc' ? 1 : -1 } }
const result = await jobsCollection.find(query, options).skip(page * size).limit(size).toArray();
res.send(result);
})
//Get all jobs data count from db
app.get('/jobs-count', async (req, res) => {
const filter = req.query.filter;
const search = req.query.search;
let query = {
job_title: { $regex: search, $options: 'i' },
};
if (filter) query.category = filter;
const count = await jobsCollection.countDocuments(query);
res.send({ count });
})
// 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('Hello from taskSphere server.......');
})
app.listen(port, () => console.log(`Server running on port ${port}`))