import { Inject, Injectable, Logger } from '@nestjs/common'; import { readFile, unlink } from 'fs/promises'; import { imageSize } from 'image-size'; import { join } from 'path'; import { Repository } from 'typeorm'; import { User } from '../user/user.entity'; import { Upload } from './upload.entity'; @Injectable() export class UploadService { public uploadPath = join(__dirname, '..', '..', '..', '..', 'uploads'); constructor( @Inject('UPLOAD_REPOSITORY') private uploadRepository: Repository, ) {} public async registerUploadedFile( file: Express.Multer.File, user: User, ): Promise { const upload = new Upload(); upload.file = file.filename; upload.original_name = file.originalname; upload.mimetype = file.mimetype; upload.uploader = user; await this.uploadRepository.insert(upload); return upload; } public async getById(id: number): Promise { return this.uploadRepository.findOne({ where: { id } }); } public async getByFile(file: string): Promise { return this.uploadRepository.findOne({ where: { file } }); } public async checkImageAspect(file: Express.Multer.File): Promise { const opened = file.buffer || (await readFile(file.path)); return new Promise((resolve) => { const result = imageSize(opened); if (result.height / result.width !== 1) { return resolve(false); } resolve(true); }); } public async delete(upload: Upload): Promise { const path = join(this.uploadPath, upload.file); try { await unlink(path); } catch (e: unknown) { Logger.error('Failed to unlink avatar file:', (e as Error).stack); } await this.uploadRepository.remove(upload); } }