|
1 | 1 | import { NextFunction, Request, Response } from 'express';
|
2 |
| - |
3 | 2 | import fs from 'fs';
|
| 3 | +import { Document } from 'mongoose'; |
4 | 4 | import multer from 'multer';
|
5 | 5 | import path from 'path';
|
6 | 6 | import { APP_ROOT } from '../../config';
|
7 | 7 | import { Product } from '../../models';
|
8 | 8 | import CustomErrorHandler from '../../services/CustomErrorHandler';
|
9 | 9 | import { productValidator } from '../../validation';
|
| 10 | +interface IProductDocument extends Document { |
| 11 | + _doc: { |
| 12 | + image: string; |
| 13 | + }; |
| 14 | +} |
10 | 15 | //[+]1. Setting up multer function
|
11 | 16 | /* The `storage` variable is an instance of `multer.diskStorage`, which is a storage engine for
|
12 | 17 | `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) => {
|
174 | 179 |
|
175 | 180 | const id = req.params.id;
|
176 | 181 |
|
177 |
| - const product = await Product.findByIdAndDelete(id); |
| 182 | + const product = (await Product.findByIdAndDelete(id)) as IProductDocument; |
178 | 183 |
|
179 | 184 | if (!product)
|
180 | 185 | throw CustomErrorHandler.notFound(`Product with id:${id} not found!`);
|
181 | 186 |
|
182 | 187 | //[] delete image from the server (or other storage location)
|
183 | 188 |
|
184 | 189 | // 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; |
187 | 192 |
|
188 | 193 | fs.unlink(`${APP_ROOT}/${filePath}`, (err) => {
|
189 | 194 | if (err) throw CustomErrorHandler.multerError('Could not delete file');
|
|
0 commit comments