Files
heala-backend/src/modules/tests/providers/tests-query.provider.ts
T

99 lines
2.4 KiB
TypeScript

import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { 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';
@Injectable()
export class TestsQueryProvider {
constructor(
/**
* Inject Tests Repository
*/
@InjectRepository(Test)
private readonly testRepository: Repository<Test>,
) {}
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 },
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) {
try {
return await this.testRepository.findOneBy({ id });
} catch (err) {
throw new AppTimeoutException(err);
}
}
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 NotFoundException('tests.errors.testNotFound');
}
return test;
}
}