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

105 lines
2.7 KiB
TypeScript

import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Form } from './entity/form.entity';
import { CreateFormDto } from './dto/create-form.dto';
import { UpdateFormDto } from './dto/update-form.dto';
@Injectable()
export class FormService {
constructor(
@InjectRepository(Form)
private readonly formRepo: Repository<Form>,
) {}
async create(data: CreateFormDto): Promise<Form> {
const form = this.formRepo.create({
...data,
});
return await this.formRepo.save(form);
}
async findAll(
page = 1,
limit = 10,
): Promise<{
docs: Form[];
totalDocs: number;
limit: number;
page: number;
totalPages: number;
hasNextPage: boolean;
hasPrevPage: boolean;
nextPage: number | null;
prevPage: number | null;
}> {
const [docs, totalDocs] = await this.formRepo.findAndCount({
skip: (page - 1) * limit,
take: limit,
relations: [
'pages',
'pages.formSections',
'pages.formSections.attachments',
'pages.formSections.questions',
'pages.formSections.questions.options',
'pages.formSections.questions.answers',
'participants', // Load participants
], // Load nested relations
});
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<Form | null> {
const form = await this.formRepo.findOne({
where: { id },
relations: [
'pages',
'pages.formSections',
'pages.formSections.attachments',
'pages.formSections.questions',
'pages.formSections.questions.options',
'pages.formSections.questions.answers',
'participants',
], // Load nested relations
});
if (!form) {
throw new NotFoundException(`Form with ID "${id}" not found`);
}
return form;
}
async update(
id: string,
data: UpdateFormDto,
): Promise<Form | null> {
const result = await this.formRepo.update(
{ id },
{ ...data, updatedAt: new Date() },
);
if (result.affected === 0) {
throw new NotFoundException(`Form with ID "${id}" not found`);
}
return await this.findById(id);
}
async remove(id: string): Promise<void> {
const result = await this.formRepo.delete({ id });
if (result.affected === 0) {
throw new NotFoundException(`Form with ID "${id}" not found`);
}
}
}