Skip to content

Commit 2e15d06

Browse files
committed
10 Aug 2023, 13:53
1 parent a4c0050 commit 2e15d06

File tree

1 file changed

+9
-4
lines changed

1 file changed

+9
-4
lines changed

src/controllers/product/productController.ts

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,17 @@
11
import { NextFunction, Request, Response } from 'express';
2-
32
import fs from 'fs';
3+
import { Document } from 'mongoose';
44
import multer from 'multer';
55
import path from 'path';
66
import { APP_ROOT } from '../../config';
77
import { Product } from '../../models';
88
import CustomErrorHandler from '../../services/CustomErrorHandler';
99
import { productValidator } from '../../validation';
10+
interface IProductDocument extends Document {
11+
_doc: {
12+
image: string;
13+
};
14+
}
1015
//[+]1. Setting up multer function
1116
/* The `storage` variable is an instance of `multer.diskStorage`, which is a storage engine for
1217
`multer` that allows you to define how files should be stored on the disk. */
@@ -174,16 +179,16 @@ const remove = async (req: Request, res: Response) => {
174179

175180
const id = req.params.id;
176181

177-
const product = await Product.findByIdAndDelete(id);
182+
const product = (await Product.findByIdAndDelete(id)) as IProductDocument;
178183

179184
if (!product)
180185
throw CustomErrorHandler.notFound(`Product with id:${id} not found!`);
181186

182187
//[] delete image from the server (or other storage location)
183188

184189
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
185-
186-
const filePath = product.image;
190+
//[+]2. Get the path of the image file stored in the db ( before getter are invoked and the dynamic APP_URL is attached)
191+
const filePath = product._doc.image;
187192

188193
fs.unlink(`${APP_ROOT}/${filePath}`, (err) => {
189194
if (err) throw CustomErrorHandler.multerError('Could not delete file');

0 commit comments

Comments
 (0)