Skip to content

Commit 3d6fe96

Browse files
committed
10 Aug 2023, 14:07
1 parent d2e3b0d commit 3d6fe96

File tree

1 file changed

+24
-17
lines changed

1 file changed

+24
-17
lines changed

src/controllers/product/productController.ts

Lines changed: 24 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -174,29 +174,36 @@ const update = async (req: Request, res: Response, next: NextFunction) => {
174174
}
175175
};
176176

177-
const remove = async (req: Request, res: Response) => {
178-
//[+]1. First get the product with the specified ID
177+
const remove = async (req: Request, res: Response, next: NextFunction) => {
178+
try {
179+
//[+]1. First get the product with the specified ID
179180

180-
const id = req.params.id;
181+
const id = req.params.id;
181182

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

184-
if (!product)
185-
throw CustomErrorHandler.notFound(`Product with id:${id} not found!`);
185+
if (!product)
186+
return next(
187+
CustomErrorHandler.notFound(`Product with id:${id} not found!`)
188+
);
186189

187-
//[] delete image from the server (or other storage location)
190+
//[] delete image from the server (or other storage location)
188191

189-
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
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;
192-
console.log(filePath);
193-
fs.unlink(`${APP_ROOT}/${filePath}`, (err) => {
194-
if (err) throw CustomErrorHandler.multerError('Could not delete file');
195-
else console.log('✅ Uploaded file deleted');
196-
});
192+
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
193+
//[+]2. Get the path of the image file stored in the db ( before getter are invoked and the dynamic APP_URL is attached)
194+
const filePath = product._doc.image;
195+
console.log(filePath);
196+
fs.unlink(`${APP_ROOT}/${filePath}`, (err) => {
197+
if (err)
198+
return next(CustomErrorHandler.multerError('Could not delete file'));
199+
else console.log('✅ Uploaded file deleted');
200+
});
197201

198-
res.json(product);
199-
//[+] 2. Delete the product if present , if not , raise error
202+
res.json(product);
203+
//[+] 2. Delete the product if present , if not , raise error
204+
} catch (err) {
205+
next(err);
206+
}
200207
};
201208

202209
const getAll = async (req: Request, res: Response) => {

0 commit comments

Comments
 (0)