Initial commit from Specify template
This commit is contained in:
55
backend/src/modules/thumbnails/thumbnails.service.ts
Normal file
55
backend/src/modules/thumbnails/thumbnails.service.ts
Normal file
@@ -0,0 +1,55 @@
|
||||
import { Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Repository } from 'typeorm';
|
||||
import { unlink } from 'fs/promises';
|
||||
import { join } from 'path';
|
||||
import { Thumbnail } from '../../entities/thumbnail.entity';
|
||||
|
||||
@Injectable()
|
||||
export class ThumbnailsService {
|
||||
constructor(
|
||||
@InjectRepository(Thumbnail)
|
||||
private thumbnailRepository: Repository<Thumbnail>,
|
||||
) {}
|
||||
|
||||
async create(file: Express.Multer.File): Promise<Thumbnail> {
|
||||
const thumbnail = this.thumbnailRepository.create({
|
||||
filePath: file.filename,
|
||||
originalName: file.originalname,
|
||||
title: file.originalname.replace(/\.[^/.]+$/, ''),
|
||||
});
|
||||
|
||||
return this.thumbnailRepository.save(thumbnail);
|
||||
}
|
||||
|
||||
async findOne(id: string): Promise<Thumbnail> {
|
||||
const thumbnail = await this.thumbnailRepository.findOne({ where: { id } });
|
||||
if (!thumbnail) {
|
||||
throw new NotFoundException(`Thumbnail with ID ${id} not found`);
|
||||
}
|
||||
return thumbnail;
|
||||
}
|
||||
|
||||
async remove(id: string): Promise<void> {
|
||||
const thumbnail = await this.findOne(id);
|
||||
|
||||
// Delete file from disk
|
||||
try {
|
||||
await unlink(join('./uploads', thumbnail.filePath));
|
||||
} catch (error) {
|
||||
console.error('Error deleting file:', error);
|
||||
}
|
||||
|
||||
await this.thumbnailRepository.remove(thumbnail);
|
||||
}
|
||||
|
||||
formatThumbnailResponse(thumbnail: Thumbnail) {
|
||||
return {
|
||||
id: thumbnail.id,
|
||||
url: `/uploads/${thumbnail.filePath}`,
|
||||
originalName: thumbnail.originalName,
|
||||
title: thumbnail.title,
|
||||
position: thumbnail.position,
|
||||
};
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user