-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
325 lines (281 loc) · 10.3 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
const express = require('express');
const cors = require('cors');
const jwt = require('jsonwebtoken');
const cookieParser = require('cookie-parser');
const { MongoClient, ServerApiVersion, ObjectId } = require('mongodb');
// all config
require('dotenv').config();
const app = express();
const port = process.env.PORT || 7000;
// all middleware
const corsConfig = {
origin: [
'http://localhost:5173',
'http://localhost:5174',
'https://glamspot-khaled.web.app',
'https://glamspot-by-khaled.vercel.app',
'https://glamspot-by-khaled.surge.sh',
'https://glamspot-by-khaled.netlify.app',
],
credentials: true,
};
app.use(cors(corsConfig));
app.use(express.json());
app.use(cookieParser());
const uri = `mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASS}@cluster0.2brfitt.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0`;
const client = new MongoClient(uri, {
serverApi: {
version: ServerApiVersion.v1,
strict: true,
deprecationErrors: true,
},
});
// my made middlewares
const verifyToken = async (req, res, next) => {
const token = req?.cookies?.token;
if (!token) {
return res.status(401).send({ message: 'unauthorized access' });
}
jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, decoded) => {
if (err) {
return res.status(401).send({ message: 'unauthorized access' });
}
if (req?.query?.email !== decoded?.email) {
return res.status(403).send({ message: 'forbidden access' });
}
next();
});
};
const cookieOptions = {
httpOnly: true,
sameSite: process.env.NODE_ENV === 'production' ? 'none' : 'strict',
secure: process.env.NODE_ENV === 'production',
};
async function run() {
try {
const serviceCollection = client.db('glamSpotDB').collection('services');
const bookingCollection = client.db('glamSpotDB').collection('bookings');
// auth related API
// node
// require('crypto').randomBytes(64).toString('hex')
// gives token when user login
app.post('/getJwtToken', async (req, res) => {
const user = req.body;
const token = jwt.sign(user, process.env.ACCESS_TOKEN_SECRET, {
expiresIn: '4h',
});
res.cookie('token', token, cookieOptions).send({ success: true });
});
// deletes token when user logout
app.post('/deleteJwtToken', async (req, res) => {
res
.clearCookie('token', { ...cookieOptions, maxAge: 0 })
.send({ success: true });
});
// services related API
// post a service
app.post('/add-service', verifyToken, async (req, res) => {
const newService = req.body;
const result = await serviceCollection.insertOne(newService);
res.send(result);
});
// Get all services
app.get('/all-services', async (req, res) => {
const result = await serviceCollection.find().toArray();
res.send(result);
});
// Get service details
app.get('/service-details/:id', async (req, res) => {
const Id = req.params.id;
const query = { _id: new ObjectId(Id) };
const result = await serviceCollection.findOne(query);
res.send(result);
});
// get my service
app.get('/my-services', verifyToken, async (req, res) => {
// use req?.query?.email istead of req?.user?.email
// because in verifyToken there is no req.user.email
const result = await serviceCollection
.find({ providerEmail: req?.query?.email })
.toArray();
res.send(result);
});
//update a service
app.patch('/update-service/:id', verifyToken, async (req, res) => {
const ID = req.params.id;
const query = { _id: new ObjectId(ID) };
const result = await serviceCollection.updateOne(query, {
$set: req.body,
});
res.send(result);
});
// delete a service
app.delete('/delete-service/:id', verifyToken, async (req, res) => {
const id = req.params.id;
const query = { _id: new ObjectId(id) };
const result = await serviceCollection.deleteOne(query);
res.send(result);
});
// Get services by pagination
app.get('/all-services-by-pagination', async (req, res) => {
const size = parseInt(req.query.size);
const page = parseInt(req.query.page) - 1;
const sort = req.query.sort;
let options = {};
if (sort) options = { sort: { serviceName: sort === 'asc' ? 1 : -1 } };
const result = await serviceCollection
.find({}, options)
.skip(page * size)
.limit(size)
.toArray();
res.send(result);
});
// Get services count
app.get('/services-count', async (req, res) => {
const count = await serviceCollection.countDocuments();
res.send({ count });
});
// Get search results
app.get('/search-services', async (req, res) => {
const search = req.query.search;
const query = {
serviceName: { $regex: search, $options: 'i' },
};
const result = await serviceCollection.find(query).toArray();
res.send(result);
});
// post a booking
app.post('/book-now', verifyToken, async (req, res) => {
const newBooking = req.body;
const result = await bookingCollection.insertOne(newBooking);
// increase booking count 1 in service collection
const updateDoc = { $inc: { totalBookings: 1 } };
const serviceQuery = { _id: new ObjectId(newBooking.serviceId) };
const updateBidCount = await serviceCollection.updateOne(
serviceQuery,
updateDoc
);
res.send(result);
});
// get my bookings
app.get('/bookings', verifyToken, async (req, res) => {
const query = {
customerEmail: req?.query?.email,
};
const result = await bookingCollection.find(query).toArray();
res.send(result);
});
// Get booking details
app.get('/booking-details/:id', verifyToken, async (req, res) => {
const BookingID = req.params.id;
const query = { _id: new ObjectId(BookingID) };
const result = await bookingCollection.findOne(query);
res.send(result);
});
// update my booking
app.patch('/update-booking/:id', verifyToken, async (req, res) => {
const BookingID = req.params.id;
const filter = { _id: new ObjectId(BookingID) };
// const jobData = req.body;
// const updateData = { $set: {...jobData} };
const updateData = { $set: req.body };
const result = await bookingCollection.updateOne(filter, updateData);
res.send(result);
});
// delete my booking
app.delete('/delete-booking/:id', verifyToken, async (req, res) => {
const query = {
_id: new ObjectId(req.params.id),
};
// decrease booking count 1 in service collection
const paiyaGesi = await bookingCollection.findOne(query);
const updateDoc = { $inc: { totalBookings: -1 } };
const serviceQuery = { _id: new ObjectId(paiyaGesi.serviceId) };
const updateBidCount = await serviceCollection.updateOne(
serviceQuery,
updateDoc
);
const result = await bookingCollection.deleteOne(query);
res.send(result);
});
// get servies-to-do from booking collection
app.get('/services-to-do', verifyToken, async (req, res) => {
const result = await bookingCollection
.find({ providerEmail: req?.query?.email })
.toArray();
res.send(result);
});
// update service status
app.patch('/update-service-status/:id', verifyToken, async (req, res) => {
const ID = req.params.id;
const query = { _id: new ObjectId(ID) };
const updateData = { $set: { serviceStatus: req.body.newStatus } };
const result = await bookingCollection.updateOne(query, updateData);
res.send(result);
});
//------------------------------------------------------------------------------------------
// app.get('/services/:id', async (req, res) => {
// const Id = req.params.id;
// const query = { _id: new ObjectId(Id) };
// const options = {
// Sort returned documents in ascending order by title (A->Z)
// sort: { title: 1 },
// Sort returned documents in ascending order by title (Z->A)
// sort: { title: -1 },
// (id na caile _id:0 dite hoy coz by default eta diye day... onno ja ja cai tar por 1 dite hobe)
// projection: { _id: 0, title: 1, imdb: 1 },
// projection: { img: 1, title: 1, price: 1 },
// };
// const result = await serviceCollection.findOne(query, options);
// res.send(result);
// });
// bookings related API
// app.get('/bookings', verifyToken, async (req, res) => {
// // console.log(req.query.email);
// // console.log('tok tok token', req?.cookies?.token);
// if (req.query.email !== req.user.email) {
// return res.status(403).send({ message: 'forbidden access' });
// }
// let query = {};
// if (req.query?.email) {
// query = { email: req.query.email };
// // query.email = req.query.email
// }
// const result = await bookingCollection.find(query).toArray();
// res.send(result);
// });
// app.post('/bookings', async (req, res) => {
// const newBooking = req.body;
// const result = await bookingCollection.insertOne(newBooking);
// res.send(result);
// });
// app.patch('/bookings/:id', async (req, res) => {
// const id = req.params.id;
// const filter = { _id: new ObjectId(id) };
// const updateData = { $set: { status: req.body.status } };
// const result = await bookingCollection.updateOne(filter, updateData);
// res.send(result);
// });
// app.delete('/bookings/:id', async (req, res) => {
// const id = req.params.id;
// const query = { _id: new ObjectId(id) };
// const result = await bookingCollection.deleteOne(query);
// res.send(result);
// });
// Send a ping to confirm a successful connection to DB
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('Hellow! From GlamSpot server owner Khaled');
});
app.listen(port, () => {
console.log(`GlamSpot server is running on port: ${port}`);
});