-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbooking.controller.ts
More file actions
76 lines (67 loc) · 2.01 KB
/
booking.controller.ts
File metadata and controls
76 lines (67 loc) · 2.01 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
import { Response } from "express";
import { Booking } from "../models/booking.model";
import { Ride } from "../models/ride.model";
import { Types } from "mongoose";
import { AuthRequest } from "../middleware/auth.middleware";
import { isUserInRide } from "../utils/rideUtils";
import { StatusCodes } from "http-status-codes";
import { ICreateBookingPayload } from "@/schemas/bookingSchema";
export class BookingController {
static async createBooking(
req: AuthRequest<{}, {}, ICreateBookingPayload>,
res: Response
) {
try {
const { rideId } = req.body;
const passengerId = req.user?.userId;
if (!Types.ObjectId.isValid(rideId)) {
return res.error("Invalid Ride ID", StatusCodes.BAD_REQUEST);
}
const rideDoc = await Ride.findById(rideId);
if (!rideDoc) {
return res.error("Ride not found", StatusCodes.NOT_FOUND);
}
if (!rideDoc.isBookable()) {
return res.error(
"Ride is not available for booking.",
StatusCodes.BAD_REQUEST
);
}
if (rideDoc.driver.toString() === passengerId) {
return res.error(
"Driver cannot book their own ride.",
StatusCodes.BAD_REQUEST
);
}
if (await isUserInRide(passengerId!, rideId)) {
return res.error(
"User already in ride or has pending booking.",
StatusCodes.BAD_REQUEST
);
}
rideDoc.passengers.push({
user: new Types.ObjectId(passengerId),
seatsBooked: 1,
status: "pending",
});
await rideDoc.save();
const booking = await Booking.create({
passenger: passengerId,
driver: rideDoc.driver,
ride: rideId,
status: "pending",
});
return res.success(
{ status: booking.status },
"Booking created successfully.",
StatusCodes.CREATED
);
} catch (error) {
return res.error(
"Server Error",
StatusCodes.INTERNAL_SERVER_ERROR,
error
);
}
}
}