import { Injectable, NotFoundException } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { Repository } from 'typeorm'; import { Question } from './entity/question.entity'; import { CreateQuestionDto } from './dto/create-question.dto'; import { UpdateQuestionDto } from './dto/update-question.dto'; @Injectable() export class QuestionService { constructor( @InjectRepository(Question) private readonly questionRepo: Repository, ) {} async create(data: CreateQuestionDto): Promise { const question = this.questionRepo.create(data); return this.questionRepo.save(question); } async findAll(page = 1, limit = 10) { const [docs, totalDocs] = await this.questionRepo.findAndCount({ skip: (page - 1) * limit, take: limit, }); const totalPages = Math.ceil(totalDocs / limit); return { docs, totalDocs, limit, page, totalPages, hasNextPage: page < totalPages, hasPrevPage: page > 1, nextPage: page < totalPages ? page + 1 : null, prevPage: page > 1 ? page - 1 : null, }; } async findById(id: string): Promise { const question = await this.questionRepo.findOneBy({ id }); if (!question) { throw new NotFoundException(`Question with ID "${id}" not found`); } return question; } async update(id: string, data: UpdateQuestionDto): Promise { await this.questionRepo.update(id, data); return this.findById(id); } async remove(id: string): Promise { const result = await this.questionRepo.delete(id); if (result.affected === 0) { throw new NotFoundException(`Question with ID "${id}" not found`); } } }