forked from Deen-Bridge/dnb-backend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcourseController.js
More file actions
236 lines (198 loc) · 7 KB
/
Copy pathcourseController.js
File metadata and controls
236 lines (198 loc) · 7 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
import Course from "../../models/Course.js";
import mongoose from "mongoose";
import logger from "../../config/logger.js";
import { catchAsync, APIError } from "../../middlewares/errorHandler.js";
import { getCacheOrSet, CACHE_TTL, CACHE_KEYS } from "../../utils/cache.js";
import { createNewCourseNotification } from "../notificationController.js";
/**
* Create a new course
* Note: Files are uploaded from frontend directly to Cloudinary
* Backend receives URLs instead of file buffers
*/
export const createCourse = catchAsync(async (req, res, next) => {
const { title, description, category, price, thumbnail, video } = req.body;
logger.info(`Creating course: ${title} by user: ${req.user._id}`);
// Validate required fields
if (!title || !description || !category) {
return next(
new APIError("Title, description, and category are required", 400)
);
}
// Create course with URLs from frontend
const course = await Course.create({
title,
description,
category,
price: price || 0,
createdBy: req.user._id,
thumbnail: thumbnail || null, // URL from frontend
video: video || null, // URL from frontend
});
logger.info(`✅ Course created successfully: ${course._id} - ${title}`);
// Emit new course notification asynchronously to followers
createNewCourseNotification(course._id, req.user._id, course.title).catch((err) =>
logger.error("Error creating course notification:", err)
);
res.status(201).json({
success: true,
message: "Course created successfully",
course,
});
});
// 📚 Get all courses
export const getCourses = async (_req, res) => {
try {
const courses = await Course.find().populate(
"createdBy",
"name email avatar"
);
res.status(200).json({ success: true, courses });
} catch (error) {
res.status(500).json({ success: false, message: error.message });
}
};
// 📘 Get a single course
export const getCourseById = async (req, res) => {
try {
const course = await Course.findById(req.params.id).populate("createdBy", "name avatar bio");
if (!course)
return res
.status(404)
.json({ success: false, message: "Course not found" });
res.status(200).json({ success: true, course });
} catch (error) {
res.status(500).json({ success: false, message: error.message });
}
};
// 📘 Get all courses created by a specific user
export const getCoursesByUser = async (req, res) => {
logger.info("⚡ Reached getCoursesByUser handler");
try {
const { createdBy } = req.query;
if (!createdBy) {
logger.info("❌ Missing user ID");
return res
.status(400)
.json({ success: false, message: "Missing user id" });
}
// Extra safety to avoid invalid ObjectId crashes
if (!mongoose.Types.ObjectId.isValid(createdBy)) {
logger.info("❌ Invalid ObjectId format");
return res
.status(400)
.json({ success: false, message: "Invalid user ID format" });
}
logger.info("✅ Finding courses...");
const courses = await Course.find({ createdBy }).populate("createdBy", "name avatar bio");
if (!courses || courses.length === 0) {
return res
.status(200)
.json({ success: false, message: "No courses found" });
}
res.status(200).json({ success: true, courses });
} catch (error) {
logger.error("❌ Unexpected Error in getCoursesByUser:", error);
res.status(500).json({ success: false, message: error.message });
}
};
// 📥 Enroll a user in a course (Purchase/Enroll)
export const enrollInCourse = async (req, res) => {
try {
const course = await Course.findById(req.params.id);
if (!course)
return res
.status(404)
.json({ success: false, message: "Course not found" });
if (course.enrolledUsers.includes(req.user._id)) {
return res
.status(400)
.json({ success: false, message: "Already enrolled" });
}
// Add user to course's enrolledUsers
course.enrolledUsers.push(req.user._id);
await course.save();
// Also add to user's purchasedCourses
const User = (await import("../../models/User.js")).default;
const user = await User.findById(req.user._id);
if (user) {
const alreadyPurchased = user.purchasedCourses.some(
(p) => p.courseId.toString() === course._id.toString()
);
if (!alreadyPurchased) {
user.purchasedCourses.push({
courseId: course._id,
purchaseDate: new Date(),
});
await user.save();
}
}
res
.status(200)
.json({
success: true,
message:
"Course purchased successfully! You can now access the full content.",
course,
});
} catch (error) {
res.status(500).json({ success: false, message: error.message });
}
};
// 📝 Edit/Update a course
export const updateCourse = catchAsync(async (req, res, next) => {
const { title, description, category, price, thumbnail, video } = req.body;
const courseId = req.params.id;
logger.info(`Updating course: ${courseId}`);
const course = await Course.findById(courseId);
if (!course) {
return next(new APIError("Course not found", 404));
}
// Check if user is the creator or admin (authorization)
if (req.user.role !== "admin" && course.createdBy.toString() !== req.user._id.toString()) {
logger.warn(`Unauthorized course update attempt by user: ${req.user._id}`);
return next(
new APIError("You are not authorized to update this course", 403)
);
}
// Update fields (URLs from frontend)
course.title = title || course.title;
course.description = description || course.description;
course.category = category || course.category;
course.price = price !== undefined ? price : course.price;
// Update media URLs if provided
if (thumbnail) course.thumbnail = thumbnail;
if (video) course.video = video;
await course.save();
logger.info(`✅ Course updated successfully: ${courseId}`);
res.status(200).json({
success: true,
message: "Course updated successfully",
course,
});
});
export {
addCourseReview,
getCourseReviews,
updateCourseReview,
deleteCourseReview,
} from "../reviewController.js";
// recommended courses for user based on their profile interest
export const fetchRecommendedCourses = async (req, res) => {
try {
const { interests } = req.body;
const hasInterests = Array.isArray(interests) && interests.length > 0;
// This endpoint is POST (interests come in the body), so the shared
// cacheMiddleware (GET-only) can't key off req.query - cache explicitly here instead.
const cacheKey = hasInterests
? `${CACHE_KEYS.COURSES}recommended:${[...interests].sort().join(",")}`
: `${CACHE_KEYS.COURSES}recommended:none`;
const recommended = await getCacheOrSet(
cacheKey,
() => Course.find({ category: { $in: interests } }),
CACHE_TTL.COURSES
);
res.status(200).json({ success: true, recommended });
} catch (e) {
res.status(500).json({ success: false, message: e.message });
}
};