82 lines
2.2 KiB
TypeScript
82 lines
2.2 KiB
TypeScript
import { Injectable } from '@nestjs/common';
|
|
import { filterQuestions } from '../helpers/filter-questions.helper';
|
|
import Utils from '@/common/utils';
|
|
import { FindQuestionsDTO } from '../dtos/find-questions.dto';
|
|
import { Test } from '@nestjs/testing';
|
|
import { AppTimeoutException } from '@/common/exceptions/app-timeout.exception';
|
|
import { PaginatedResponse } from '@/common/responses';
|
|
import { InjectRepository } from '@nestjs/typeorm';
|
|
import { Question } from '../entities/question.entity';
|
|
import { Repository } from 'typeorm';
|
|
import { TestsService } from '@/modules/tests/providers/tests.service';
|
|
|
|
@Injectable()
|
|
export class QuestionsQueryProvider {
|
|
constructor(
|
|
/**
|
|
* Inject Questions Repository
|
|
*/
|
|
@InjectRepository(Question)
|
|
private readonly questionsRepository: Repository<Question>,
|
|
|
|
/**
|
|
* Inject Tests Service
|
|
*/
|
|
private readonly testsService: TestsService,
|
|
) {}
|
|
|
|
public async findAllForAdmin(query: FindQuestionsDTO) {
|
|
const filters = filterQuestions(query);
|
|
const { limit, page, skip, take } =
|
|
Utils.PaginationUtils.getPaginationOptions(query);
|
|
|
|
let selectedTest: Test | null = null;
|
|
|
|
if (query.test) {
|
|
try {
|
|
selectedTest = await this.testsService.adminGetOne(query.test);
|
|
} catch (err) {
|
|
throw new AppTimeoutException(err);
|
|
}
|
|
}
|
|
|
|
try {
|
|
const [questions, total] = await this.questionsRepository.findAndCount({
|
|
where: {
|
|
...filters,
|
|
...(selectedTest && {
|
|
test: selectedTest,
|
|
}),
|
|
},
|
|
loadRelationIds: true,
|
|
skip,
|
|
take,
|
|
order: query.sortBy
|
|
? {
|
|
[query.sortBy]: query.order ?? 'ASC',
|
|
}
|
|
: { createdAt: 'DESC' },
|
|
});
|
|
|
|
return new PaginatedResponse(questions, {
|
|
page,
|
|
limit,
|
|
total,
|
|
});
|
|
} catch (err) {
|
|
throw new AppTimeoutException(err);
|
|
}
|
|
}
|
|
|
|
public async findOneForAdmin(id: number) {
|
|
try {
|
|
return await this.questionsRepository.findOne({
|
|
where: { id },
|
|
relations: { test: true },
|
|
});
|
|
} catch (err) {
|
|
throw new AppTimeoutException(err);
|
|
}
|
|
}
|
|
}
|