93 lines
2.8 KiB
TypeScript
93 lines
2.8 KiB
TypeScript
import { Injectable, NotFoundException } from '@nestjs/common';
|
|
import { InjectRepository } from '@nestjs/typeorm';
|
|
import { Repository } from 'typeorm';
|
|
import { Answer } from './entity/answer.entity';
|
|
import { CreateAnswerDto } from './dto/create-answer.dto';
|
|
import { UpdateAnswerDto } from './dto/update-answer.dto';
|
|
|
|
@Injectable()
|
|
export class AnswerService {
|
|
constructor(
|
|
@InjectRepository(Answer)
|
|
private readonly answerRepository: Repository<Answer>,
|
|
) {}
|
|
|
|
async create(data: CreateAnswerDto): Promise<Answer> {
|
|
try {
|
|
const answer = this.answerRepository.create({ ...data });
|
|
return await this.answerRepository.save(answer);
|
|
} catch (error) {
|
|
throw new Error(`Failed to create answer: ${error.message}`);
|
|
}
|
|
}
|
|
|
|
async findAll( page = 1, limit = 10 ): Promise<{
|
|
docs: Answer[];
|
|
totalDocs: number;
|
|
limit: number;
|
|
page: number;
|
|
totalPages: number;
|
|
hasNextPage: boolean;
|
|
hasPrevPage: boolean;
|
|
nextPage: number | null;
|
|
prevPage: number | null;
|
|
}> {
|
|
try {
|
|
const skip = (page - 1) * limit;
|
|
const [docs, totalDocs] = await this.answerRepository.findAndCount({
|
|
skip,
|
|
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,
|
|
};
|
|
} catch (error) {
|
|
throw new Error(`Failed to fetch answers: ${error.message}`);
|
|
}
|
|
}
|
|
|
|
async findById(id: string): Promise<Answer | null> {
|
|
try {
|
|
const answer = await this.answerRepository.findOne({ where: { id } });
|
|
if (!answer) {
|
|
throw new NotFoundException(`Answer with ID "${id}" not found`);
|
|
}
|
|
return answer;
|
|
} catch (error) {
|
|
throw new Error(`Failed to find answer: ${error.message}`);
|
|
}
|
|
}
|
|
|
|
async update(id: string, data: UpdateAnswerDto): Promise<Answer | null> {
|
|
try {
|
|
await this.answerRepository.update({ id }, { ...data, updatedAt: new Date() });
|
|
const updatedAnswer = await this.answerRepository.findOne({ where: { id } });
|
|
if (!updatedAnswer) {
|
|
throw new NotFoundException(`Answer with ID "${id}" not found`);
|
|
}
|
|
return updatedAnswer;
|
|
} catch (error) {
|
|
throw new Error(`Failed to update answer: ${error.message}`);
|
|
}
|
|
}
|
|
|
|
async remove(id: string): Promise<void> {
|
|
try {
|
|
const result = await this.answerRepository.delete({ id });
|
|
if (result.affected === 0) {
|
|
throw new NotFoundException(`Answer with ID "${id}" not found`);
|
|
}
|
|
} catch (error) {
|
|
throw new Error(`Failed to delete answer: ${error.message}`);
|
|
}
|
|
}
|
|
} |