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

View File

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