Form-Service/src/question/question.service.ts

60 lines
1.7 KiB
TypeScript

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<Question>,
) {}
async create(data: CreateQuestionDto): Promise<Question> {
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<Question | null> {
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<Question | null> {
await this.questionRepo.update(id, data);
return this.findById(id);
}
async remove(id: string): Promise<void> {
const result = await this.questionRepo.delete(id);
if (result.affected === 0) {
throw new NotFoundException(`Question with ID "${id}" not found`);
}
}
}