feat: Create course and automatically assign the creator as the primary instructor using a transaction.

This commit is contained in:
JakkrapartXD 2026-01-19 14:48:45 +07:00
parent a38389cc9f
commit 715d94fbf9

View file

@ -26,25 +26,40 @@ import {
export class CoursesInstructorService {
static async createCourse(courseData: CreateCourseInput, userId: number): Promise<createCourseResponse> {
try {
// Map custom input to Prisma format
const courseCreated = await prisma.course.create({
data: {
category_id: courseData.category_id,
title: courseData.title,
slug: courseData.slug,
description: courseData.description,
thumbnail_url: courseData.thumbnail_url,
price: courseData.price || 0,
is_free: courseData.is_free ?? false,
have_certificate: courseData.have_certificate ?? false,
created_by: userId, // Required field from JWT
status: 'DRAFT' // Default status
}
// Use transaction to create course and instructor together
const result = await prisma.$transaction(async (tx) => {
// Create the course
const courseCreated = await tx.course.create({
data: {
category_id: courseData.category_id,
title: courseData.title,
slug: courseData.slug,
description: courseData.description,
thumbnail_url: courseData.thumbnail_url,
price: courseData.price || 0,
is_free: courseData.is_free ?? false,
have_certificate: courseData.have_certificate ?? false,
created_by: userId,
status: 'DRAFT'
}
});
// Add creator as primary instructor
await tx.courseInstructor.create({
data: {
course_id: courseCreated.id,
user_id: userId,
is_primary: true,
}
});
return courseCreated;
});
return {
code: 201,
message: 'Course created successfully',
data: courseCreated
data: result
};
} catch (error) {
logger.error('Failed to create course', { error });