import { Injectable, NotFoundException } from '@nestjs/common'; import { InjectModel } from '@nestjs/mongoose'; import { Model } from 'mongoose'; import { Form, FormDocument } from './entity/form.entity'; import { CreateFormDto } from './dto/create-form.dto'; import { UpdateFormDto } from './dto/update-form.dto'; import { PaginateModel } from '../participant/participant.service'; @Injectable() export class FormService { constructor( @InjectModel(Form.name) private readonly formModel: PaginateModel, ) {} async create(data: CreateFormDto): Promise
{ const form = new this.formModel({ ...data, id: data.id || undefined, // Let BaseEntity generate UUID if not provided metadata: data.metadata || { entries: [] }, }); return form.save(); } 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; }> { // Selects all fields from the Form entity for the response return this.formModel.paginate( {}, { page, limit, lean: true }, ); } async findById(id: string): Promise { const form = await this.formModel .findOne({ id }) .lean() .exec(); if (!form) { throw new NotFoundException(`Form with ID "${id}" not found`); } return form; } async update( id: string, data: UpdateFormDto, ): Promise { const updatedForm = await this.formModel .findOneAndUpdate( { id }, { $set: { ...data, updatedAt: new Date() } }, { new: true }, ) .lean() .exec(); if (!updatedForm) { throw new NotFoundException(`Form with ID "${id}" not found`); } return updatedForm; } async remove(id: string): Promise { const result = await this.formModel.deleteOne({ id }).exec(); if (result.deletedCount === 0) { throw new NotFoundException(`Form with ID "${id}" not found`); } } }