-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
313 lines (275 loc) · 8.77 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
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const jwt = require("jsonwebtoken");
const { MongoClient, ObjectId } = require("mongodb");
const stripe = require("stripe")(process.env.STRIPE_SECRET_KEY);
require("dotenv").config();
const app = express();
//port
const port = process.env.PORT || 5000;
// Middleware for parsing request bodies
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(cors());
// MongoDB connection URL
const databaseURL = process.env.MONGO;
// Create a MongoClient instance
const client = new MongoClient(databaseURL);
function verifyJWT(req, res, next) {
const authHeader = req.headers.authorization;
if (!authHeader) {
return res.status(401).send("unauthorized access");
}
const token = authHeader.split(" ")[1];
console.log(token);
jwt.verify(token, process.env.ACCESS_TOKEN, function (err, decoded) {
if (err) {
return res.status(403).send({ message: "forbidden access" });
}
req.decoded = decoded;
next();
});
}
async function mainFunc() {
try {
// Connect to MongoDB
await client.connect();
console.log("Connected to MongoDB");
// Access the database and collection
const database = client.db("doctorsPortal");
const usersCollection = database.collection("users");
const appointmentOptionCollection =
database.collection("appointmentOptions");
const bookingsCollection = database.collection("bookings");
const doctorsCollection = database.collection("doctors");
const paymentsCollection = database.collection("payments");
const verifyAdmin = async (req, res, next) => {
const decodedEmail = req.decoded.email;
const query = { email: decodedEmail };
const user = await usersCollection.findOne(query);
if (user?.role !== "admin") {
return res.status(403).send({ message: "forbidden access" });
}
next();
};
app.get("/appointmentOptions", async (req, res) => {
const date = req.query.date;
const query = {};
const options = await appointmentOptionCollection.find(query).toArray();
// get the bookings of the provided date
const bookingQuery = { appointmentDate: date };
const alreadyBooked = await bookingsCollection
.find(bookingQuery)
.toArray();
// code carefully :D
options.forEach((option) => {
const optionBooked = alreadyBooked.filter(
(book) => book.treatment === option.name
);
const bookedSlots = optionBooked.map((book) => book.slot);
const remainingSlots = option.slots.filter(
(slot) => !bookedSlots.includes(slot)
);
option.slots = remainingSlots;
});
res.send(options);
});
app.get("/v2/appointmentOptions", async (req, res) => {
const date = req.query.date;
const options = await appointmentOptionCollection
.aggregate([
{
$lookup: {
from: "bookings",
localField: "name",
foreignField: "treatment",
pipeline: [
{
$match: {
$expr: {
$eq: ["$appointmentDate", date],
},
},
},
],
as: "booked",
},
},
{
$project: {
name: 1,
price: 1,
slots: 1,
image: 1,
specialty: 1,
booked: {
$map: {
input: "$booked",
as: "book",
in: "$$book.slot",
},
},
},
},
{
$project: {
name: 1,
price: 1,
slots: {
$setDifference: ["$slots", "$booked"],
},
image: 1,
specialty: 1,
},
},
])
.toArray();
res.send(options);
});
app.get("/appointmentSpecialty", async (req, res) => {
const query = {};
const result = await appointmentOptionCollection
.find(query)
.project({ specialty: 1 })
.toArray();
console.log(result);
res.send(result);
});
app.get("/bookings", verifyJWT, async (req, res) => {
const email = req.query.email;
const decodedEmail = req.decoded.email;
if (email !== decodedEmail) {
return res.status(403).send({ message: "forbidden access" });
}
const query = { email: email };
const bookings = await bookingsCollection.find(query).toArray();
res.send(bookings);
});
app.get("/bookings/:id", async (req, res) => {
const id = req.params.id;
const query = { _id: ObjectId(id) };
const booking = await bookingsCollection.findOne(query);
res.send(booking);
});
app.post("/bookings", async (req, res) => {
const booking = req.body;
console.log(booking);
const query = {
appointmentDate: booking.appointmentDate,
email: booking.email,
treatment: booking.treatment,
};
const alreadyBooked = await bookingsCollection.find(query).toArray();
if (alreadyBooked.length) {
const message = `You already have a booking on ${booking.appointmentDate}`;
return res.send({ acknowledged: false, message });
}
const result = await bookingsCollection.insertOne(booking);
// send email about appointment confirmation
sendBookingEmail(booking);
res.send(result);
});
app.get("/jwt", async (req, res) => {
const email = req.query.email;
const query = { email: email };
const user = await usersCollection.findOne(query);
if (user) {
const token = jwt.sign({ email }, process.env.ACCESS_TOKEN, {
expiresIn: "1h",
});
return res.send({ accessToken: token });
}
res.status(403).send({ accessToken: "" });
});
app.get("/users", async (req, res) => {
const query = {};
const users = await usersCollection.find(query).toArray();
res.send(users);
});
app.post("/users", async (req, res) => {
const user = req.body;
const result = await usersCollection.insertOne(user);
res.send(result);
});
app.get("/users/admin/:email", async (req, res) => {
const email = req.params.email;
const query = { email };
const user = await usersCollection.findOne(query);
res.send({ isAdmin: user?.role === "admin" });
});
app.put("/users/admin/:id", verifyJWT, verifyAdmin, async (req, res) => {
const id = req.params.id;
const filter = { _id: ObjectId(id) };
const options = { upsert: true };
const updatedDoc = {
$set: {
role: "admin",
},
};
const result = await usersCollection.updateOne(
filter,
updatedDoc,
options
);
res.send(result);
});
app.post("/doctors", verifyJWT, verifyAdmin, async (req, res) => {
const doctor = req.body;
const result = await doctorsCollection.insertOne(doctor);
res.send(result);
});
app.get("/doctors", verifyJWT, verifyAdmin, async (req, res) => {
const query = {};
const doctors = await doctorsCollection.find(query).toArray();
res.send(doctors);
});
app.delete("/doctors/:id", verifyJWT, verifyAdmin, async (req, res) => {
const id = req.params.id;
const filter = { _id: ObjectId(id) };
const result = await doctorsCollection.deleteOne(filter);
res.send(result);
});
app.post("/create-payment-intent", async (req, res) => {
const booking = req.body;
const price = booking.price;
const amount = price * 100;
const paymentIntent = await stripe.paymentIntents.create({
currency: "usd",
amount: amount,
payment_method_types: ["card"],
});
res.send({
clientSecret: paymentIntent.client_secret,
});
});
app.post("/payments", async (req, res) => {
const payment = req.body;
const result = await paymentsCollection.insertOne(payment);
const id = payment.bookingId;
const filter = { _id: ObjectId(id) };
const updatedDoc = {
$set: {
paid: true,
transactionId: payment.transactionId,
},
};
const updatedResult = await bookingsCollection.updateOne(
filter,
updatedDoc
);
res.send(result);
});
} catch (error) {
console.error(error);
}
}
mainFunc().catch(console.log());
// Serve index.html
app.get("/", (req, res) => {
res.send("hello");
});
// Start the server
app.listen(port, () => {
console.log(`Server is listening on port ${port}`);
});