58 lines
1.5 KiB
TypeScript
58 lines
1.5 KiB
TypeScript
import { Inject, Injectable } 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<Upload>,
|
|
) {}
|
|
|
|
public async registerUploadedFile(
|
|
file: Express.Multer.File,
|
|
user: User,
|
|
): Promise<Upload> {
|
|
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 checkImageAspect(file: Express.Multer.File): Promise<boolean> {
|
|
const opened = 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<void> {
|
|
const path = join(this.uploadPath, upload.file);
|
|
|
|
try {
|
|
await unlink(path);
|
|
} catch (e: any) {
|
|
console.error('Failed to unlink avatar file:', e.stack);
|
|
}
|
|
|
|
await this.uploadRepository.remove(upload);
|
|
}
|
|
}
|