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

96 lines
2.9 KiB
TypeScript

import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Attachment } from './entity/attachment.entity';
import { CreateAttachmentDto } from './dto/create_attachment.dto';
import { UpdateAttachmentDto } from './dto/update_attachment.dto';
import { AuthRequest } from '../middleware/jwtMiddleware';
@Injectable()
export class AttachmentService {
constructor(
@InjectRepository(Attachment)
private readonly attachmentRepository: Repository<Attachment>,
) {}
async create(data: CreateAttachmentDto, user: AuthRequest['user']): Promise<Attachment> {
const attachment = this.attachmentRepository.create({
...data,
ownerId: user.sub,
});
return await this.attachmentRepository.save(attachment);
}
async findAll(
page = 1,
limit = 10,
): Promise<{
docs: Attachment[];
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.attachmentRepository.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 attachments: ${error.message}`);
}
}
async findById(id: string): Promise<Attachment | null> {
try {
const attachment = await this.attachmentRepository.findOne({ where: { id } });
if (!attachment) {
throw new NotFoundException(`Attachment with ID "${id}" not found`);
}
return attachment;
} catch (error) {
throw new Error(`Failed to find attachment: ${error.message}`);
}
}
async update(id: string, data: UpdateAttachmentDto): Promise<Attachment | null> {
try {
await this.attachmentRepository.update({ id }, { ...data, updatedAt: new Date() });
const updatedAttachment = await this.attachmentRepository.findOne({ where: { id } });
if (!updatedAttachment) {
throw new NotFoundException(`Attachment with ID "${id}" not found`);
}
return updatedAttachment;
} catch (error) {
throw new Error(`Failed to update attachment: ${error.message}`);
}
}
async remove(id: string): Promise<void> {
try {
const result = await this.attachmentRepository.delete({ id });
if (result.affected === 0) {
throw new NotFoundException(`Attachment with ID "${id}" not found`);
}
} catch (error) {
throw new Error(`Failed to delete attachment: ${error.message}`);
}
}
}