11import { Injectable , NotFoundException } from '@nestjs/common' ;
22import { File } from '../entity/file.entity' ;
3- import { unlinkSync , existsSync } from 'fs' ;
3+ import { unlink , access } from 'fs/promises ' ;
44import { FileRepository } from '../repository/file.repository' ;
55import { User } from '../../user/entity/user.entity' ;
66import { FileUploadResponseDto } from '../dto/response/createFile.dto' ;
7+ import { WinstonLoggerService } from '../../common/logger/logger.service' ;
78
89@Injectable ( )
910export class FileService {
10- constructor ( private readonly fileRepository : FileRepository ) { }
11+ constructor (
12+ private readonly fileRepository : FileRepository ,
13+ private readonly logger : WinstonLoggerService ,
14+ ) { }
1115
1216 async create ( file : any , userId : number ) : Promise < FileUploadResponseDto > {
13- const { originalName , mimetype, size, path } = file ;
17+ const { originalname , mimetype, size, path } = file ;
1418
1519 const savedFile = await this . fileRepository . save ( {
16- originalName,
20+ originalName : originalname ,
1721 mimetype,
1822 size,
1923 path,
@@ -25,8 +29,7 @@ export class FileService {
2529 }
2630
2731 private generateAccessUrl ( filePath : string ) : string {
28- const baseUploadPath =
29- process . env . UPLOAD_BASE_PATH || '/var/web05-Denamu/objects' ;
32+ const baseUploadPath = '/var/web05-Denamu/objects' ;
3033 const relativePath = filePath . replace ( baseUploadPath , '' ) ;
3134 return `/objects${ relativePath } ` ;
3235 }
@@ -42,8 +45,11 @@ export class FileService {
4245 async deleteFile ( id : number ) : Promise < void > {
4346 const file = await this . findById ( id ) ;
4447
45- if ( existsSync ( file . path ) ) {
46- unlinkSync ( file . path ) ;
48+ try {
49+ await access ( file . path ) ;
50+ await unlink ( file . path ) ;
51+ } catch ( error ) {
52+ this . logger . warn ( `파일 삭제 실패: ${ file . path } ` , 'FileService' ) ;
4753 }
4854
4955 await this . fileRepository . delete ( id ) ;
@@ -52,4 +58,20 @@ export class FileService {
5258 async getFileInfo ( id : number ) : Promise < File > {
5359 return this . findById ( id ) ;
5460 }
61+
62+ async deleteByPath ( path : string ) : Promise < void > {
63+ const file = await this . fileRepository . findOne ( { where : { path } } ) ;
64+ if ( file ) {
65+ try {
66+ await access ( file . path ) ;
67+ await unlink ( file . path ) ;
68+ } catch ( error ) {
69+ this . logger . warn ( `파일 삭제 실패: ${ file . path } ` , 'FileService' ) ;
70+ }
71+
72+ await this . fileRepository . delete ( file . id ) ;
73+ } else {
74+ throw new NotFoundException ( '파일을 찾을 수 없습니다.' ) ;
75+ }
76+ }
5577}
0 commit comments