import { ConflictException, HttpStatus, Injectable } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { Question } from '../entities/question.entity'; import { DataSource, QueryFailedError, Repository } from 'typeorm'; import { TestsService } from '@/modules/tests/providers/tests.service'; import { I18nService } from 'nestjs-i18n'; import { CreateQuestionDTO } from '../dtos/create-question.dto'; import { AppResponse } from '@/common/responses'; import { UNIQUE_TEST_ORDER_IDX } from '../constants'; import { AppTimeoutException } from '@/common/exceptions/app-timeout.exception'; import { UpdateQuestionDTO } from '../dtos/update-question.dto'; import { validateMetadata } from '../helpers/validate-metadata.helper'; import { AppException } from '@/common/exceptions/app.exception'; import { Test } from '@/modules/tests/entities/test.entity'; import { QuestionType } from '../enums/question-type.enum'; @Injectable() export class QuestionsCommandProvider { constructor( /** * Inject DataSource */ private readonly dataSource: DataSource, /** * Inject Questions Repository */ @InjectRepository(Question) private readonly questionsRepository: Repository, /** * Inject Tests Service */ private readonly testsService: TestsService, /** * Inject I18n Service */ private readonly i18nService: I18nService, ) {} public async createOne(createQuestionDto: CreateQuestionDTO) { const metadataErrors = await validateMetadata( createQuestionDto.type ?? QuestionType.SINGLE_CHOICE, createQuestionDto.metadata ?? null, ); if (metadataErrors.length) throw new AppException( 'validation.wrongFieldFormat', HttpStatus.BAD_REQUEST, { field: '$t(questions.fields.metadata)' }, ); const test = await this.testsService.adminGetOne(createQuestionDto.test); const newQuestion = this.questionsRepository.create({ ...createQuestionDto, test, }); try { await this.dataSource.transaction(async (manager) => { await manager.save(newQuestion); await manager.increment(Test, { id: test.id }, 'questionsCount', 1); }); return new AppResponse( newQuestion, this.i18nService.translate('common.messages.createSuccess', { args: { entity: '$t(questions.fields.question)' }, }), ); } catch (err) { if ( err instanceof QueryFailedError && // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access (err as any).constraint === UNIQUE_TEST_ORDER_IDX ) { throw new ConflictException('questions.errors.uniqueOrderConstraint'); } throw new AppTimeoutException(err); } } public async updateOne(id: number, updateQuestionDto: UpdateQuestionDTO) { const question = await this.questionsRepository.findOneBy({ id }); if (!question) { throw new AppException( 'common.errors.entityNotFound', HttpStatus.NOT_FOUND, { entity: '$t(questions.fields.question)' }, ); } if (updateQuestionDto.test) { if (updateQuestionDto.test !== question.testId) { throw new ConflictException( 'جابجایی سؤال به آزمون دیگر مجاز نیست؛ سؤال جدید بسازید.', ); } } const type = updateQuestionDto.type !== undefined ? updateQuestionDto.type : question.type; const metadata = updateQuestionDto.metadata !== undefined ? updateQuestionDto.metadata : question.metadata; const errors = await validateMetadata(type, metadata); if (errors && errors.length > 0) { throw new AppException( 'validation.wrongFieldFormat', HttpStatus.BAD_REQUEST, { field: '$t(questions.fields.metadata)' }, ); } const changes = { ...updateQuestionDto }; delete changes.test; Object.assign(question, changes); try { return await this.questionsRepository.save(question); } catch (err) { if ( err instanceof QueryFailedError && // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access (err as any).constraint === UNIQUE_TEST_ORDER_IDX ) { throw new ConflictException('questions.errors.uniqueOrderConstraint'); } throw new AppTimeoutException(err); } } public async deleteOne(id: number) { let question: Question | null = null; try { question = await this.questionsRepository.findOne({ where: { id }, relations: { test: true }, }); } catch (err) { throw new AppTimeoutException(err); } if (!question) throw new AppException( 'common.errors.entityNotFound', HttpStatus.NOT_FOUND, { entity: '$t(questions.fields.question)' }, ); try { await this.dataSource.transaction(async (manager) => { await manager.delete(Question, question.id); await manager.decrement( Test, { id: question.test.id }, 'questionsCount', 1, ); }); } catch (err) { console.log(err); throw new AppTimeoutException(err); } } }