refactor: students count query

This commit is contained in:
Sergey Yarkov 2021-08-14 22:07:55 +03:00
parent 1bfb7ad111
commit f2b43ee388
2 changed files with 6 additions and 19 deletions

View File

@ -78,7 +78,7 @@ export default class CourseRepository {
* @param id Course id * @param id Course id
* @returns Likes count * @returns Likes count
*/ */
public async getLikesCount(id: string | number): Promise<any> { public async getLikesCount(id: string | number): Promise<BigInt> {
const likes = await this.Database.query().from('courses_likes').where('course_id', id).count('* as count'); const likes = await this.Database.query().from('courses_likes').where('course_id', id).count('* as count');
return likes[0].count; return likes[0].count;
} }
@ -138,10 +138,9 @@ export default class CourseRepository {
* @param id Course if * @param id Course if
* @returns Students count * @returns Students count
*/ */
public async getStudentsCount(id: string | number): Promise<{ count: any } | null> { public async getStudentsCount(id: string | number): Promise<BigInt> {
const course = await this.Course.query().where('id', id).withCount('students').first(); const students = await this.Database.query().from('users_courses').where('course_id', id).count('* as count');
return students[0].count;
return course && ({ count: course.$extras.students_count } ?? null);
} }
/** /**

View File

@ -209,25 +209,13 @@ export default class CourseService {
* @returns Response * @returns Response
*/ */
public async fetchStudentsCount(id: string | number): Promise<IResponse> { public async fetchStudentsCount(id: string | number): Promise<IResponse> {
const data = await this.courseRepository.getStudentsCount(id); const count = await this.courseRepository.getStudentsCount(id);
if (!data) {
return {
success: false,
status: StatusCodeEnum.NOT_FOUND,
message: 'Course not found.',
data: {},
error: {
code: 'E_NOT_FOUND',
},
};
}
return { return {
success: true, success: true,
status: StatusCodeEnum.OK, status: StatusCodeEnum.OK,
message: 'Fetched students count.', message: 'Fetched students count.',
data, data: { count },
}; };
} }