delete post picture if exist
This commit is contained in:
parent
f01baf4c2e
commit
3e1a2f6b5b
|
|
@ -1,6 +1,7 @@
|
|||
import multer from 'multer';
|
||||
import path from 'path';
|
||||
import {v4 as uuidv4} from 'uuid';
|
||||
import fs from 'fs';
|
||||
|
||||
const storage = multer.diskStorage({
|
||||
destination: path.join(__dirname, '../../public/uploads'),
|
||||
|
|
@ -10,3 +11,12 @@ const storage = multer.diskStorage({
|
|||
});
|
||||
|
||||
export const upload = multer({ storage });
|
||||
|
||||
export const deleteFile = (filename: string) => {
|
||||
const filePath = path.join(__dirname, '../../public/uploads', filename);
|
||||
fs.unlink(filePath, (err) => {
|
||||
if (err) {
|
||||
console.log(err);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
|
@ -2,6 +2,7 @@ import { PrismaClient, Post as PrismaPost, Like } from '@prisma/client';
|
|||
import { Post } from '@/models/PostModel';
|
||||
import { exclude } from '@/lib/utils';
|
||||
import { getUserById } from './UserController';
|
||||
import { deleteFile } from './FileController';
|
||||
|
||||
const prisma = new PrismaClient();
|
||||
|
||||
|
|
@ -95,6 +96,9 @@ const deletePost = async (id: number, userId: number): Promise<PrismaPost | Erro
|
|||
if (post.authorId !== userId && user.role === 'USER') {
|
||||
return new Error('User is not the author of this post');
|
||||
}
|
||||
if (post.image) {
|
||||
deleteFile(post.image);
|
||||
}
|
||||
return prisma.post.delete({
|
||||
where: {
|
||||
id,
|
||||
|
|
|
|||
Loading…
Reference in New Issue