import { HttpStatus, Injectable } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { FindOneOptions, Repository } from 'typeorm'; import { PaginatedResponse } from '@/common/responses'; import { AppTimeoutException } from '@/common/exceptions/app-timeout.exception'; import { FindTestsDTO } from '../dtos/find-tests.dto'; import { filterTests } from '../helpers/filter-tests.helper'; import Utils from '@/common/utils'; import { Test } from '../entities/test.entity'; import { AppException } from '@/common/exceptions/app.exception'; import { TestStatus } from '../enums/test-status.enum'; @Injectable() export class TestsQueryProvider { constructor( /** * Inject Tests Repository */ @InjectRepository(Test) private readonly testRepository: Repository, ) {} public async findAllForAdmin(query: FindTestsDTO) { const filterOptions = filterTests(query); const { page, take, limit, skip } = Utils.PaginationUtils.getPaginationOptions(query); try { const [tests, total] = await this.testRepository.findAndCount({ where: filterOptions, skip, take, order: query.sortBy ? { [query.sortBy]: query.order ?? 'ASC', } : { createdAt: 'DESC' }, }); return new PaginatedResponse(tests, { page, limit, total, }); } catch (err) { throw new AppTimeoutException(err); } } public async findAllForUser() { try { return await this.testRepository.find({ where: { isActive: true, status: TestStatus.PUBLISHED }, select: { id: true, accessType: true, description: true, price: true, title: true, }, order: { createdAt: 'DESC' }, }); } catch (err) { throw new AppTimeoutException(err); } } public async findOneForAdmin(id: number, options?: FindOneOptions) { let test: Test | null = null; try { test = await this.testRepository.findOne({ where: { id }, ...options, }); } catch (err) { throw new AppTimeoutException(err); } if (!test) { throw new AppException( 'common.errors.entityNotFound', HttpStatus.NOT_FOUND, { entity: '$t(tests.fields.test)' }, ); } return test; } public async findOneForUser(id: number) { let test: Test | null; try { test = await this.testRepository.findOne({ where: { id, isActive: true }, select: { id: true, accessType: true, description: true, price: true, title: true, }, }); } catch (err) { throw new AppTimeoutException(err); } if (!test) { throw new AppException( 'common.errors.entityNotFound', HttpStatus.NOT_FOUND, { entity: '$t(tests.fields.test)' }, ); } return test; } }