feat: implement course listing and retrieval API with dedicated controller, service, and types.

This commit is contained in:
JakkrapartXD 2026-01-15 17:57:32 +07:00
parent 4b335b6b49
commit 1aa3190ca4
3 changed files with 91 additions and 0 deletions

View file

@ -0,0 +1,25 @@
import { Get, Body, Post, Route, Tags, SuccessResponse, Response, Delete, Controller, Security, Request, Put, Path } from 'tsoa';
import { ValidationError } from '../middleware/errorHandler';
import { createCourse, createCourseResponse, listCourseResponse } from '../types/courses.types';
import { CoursesService } from '../services/courses.service';
import { get } from 'http';
@Route('api/courses')
@Tags('Courses')
export class CoursesController extends Controller {
private coursesService = new CoursesService();
@Get()
@SuccessResponse('200', 'Courses fetched successfully')
@Response('401', 'Invalid or expired token')
public async listCourses(): Promise<listCourseResponse> {
return await this.coursesService.ListCourses();
}
@Get('{id}')
@SuccessResponse('200', 'Course fetched successfully')
@Response('401', 'Invalid or expired token')
public async getCourseById(@Path() id: number): Promise<listCourseResponse> {
return await this.coursesService.ListCourses();
}
}

View file

@ -0,0 +1,40 @@
import { prisma } from '../config/database';
import { Prisma } from '@prisma/client';
import { config } from '../config';
import { logger } from '../config/logger';
import jwt from 'jsonwebtoken';
import { createCourse, createCourseResponse, listCourseResponse, getCourseResponse } from '../types/courses.types';
import { UnauthorizedError, ValidationError, ForbiddenError } from '../middleware/errorHandler';
export class CoursesService {
async ListCourses(): Promise<listCourseResponse> {
try {
const courses = await prisma.course.findMany();
return {
code: 200,
message: 'Courses fetched successfully',
total: courses.length,
data: courses,
};
} catch (error) {
logger.error('Failed to fetch courses', { error });
throw error;
}
}
async GetCourseById(id: number): Promise<getCourseResponse> {
try {
const course = await prisma.course.findUnique({ where: { id } });
return {
code: 200,
message: 'Course fetched successfully',
data: course,
};
} catch (error) {
logger.error('Failed to fetch course', { error });
throw error;
}
}
}

View file

@ -0,0 +1,26 @@
import { Course, Prisma } from '@prisma/client';
// Use Prisma's CourseCreateInput for creating courses
export interface createCourse {
data: Prisma.CourseCreateInput;
}
// Response type uses Prisma's Course model
export interface createCourseResponse {
code: number;
message: string;
data: Course;
}
export interface listCourseResponse {
code: number;
message: string;
data: Course[];
total: number | null;
}
export interface getCourseResponse {
code: number;
message: string;
data: Course | null;
}