feat: Create course and automatically assign the creator as the primary instructor using a transaction.
This commit is contained in:
parent
a38389cc9f
commit
715d94fbf9
1 changed files with 30 additions and 15 deletions
|
|
@ -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 });
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue