I'm trying to run an API call that deletes an image from an S3 bucket and MySQL db but running into an issue where the s3 image can't be found as it's being deleted from the database first.
// Router code:
//req.body is an array of ids. e.g. [ 213, 214]
//remove from s3
req.body.forEach((mediaId) => {
mediaService.removeMediaItem(mediaId);
});
//remove from db
await recycleBinService.deleteRecycledMedia(req.body);
Ideally this code in the router runs delete from s3 > delete from db but currently I think it's deleting from db first as the image variable in the removeMediaItem function is showing as null if I log it out.
// removeMediaItem
const removeMediaItem = async (mediaId) => {
const image = await _db.findOne("media", { id: mediaId });
console.log("image: ", image);
await s3Connection.deleteFile(image.file_name);
};
// deleteRecycledMedia
const wheresMedia = _apiDb.orWhere("id", mediaIds);
const wheresRecycle = _apiDb.orWhere("media", mediaIds);
// db Query that second input after first.
await _apiDb.doubleRawSql(
`DELETE from media ${wheresMedia}`,
`DELETE from recycle_bin ${wheresRecycle}`
);
You need to await removeMediaItem. i.e.
req.body.forEach((mediaId) => {
await mediaService.removeMediaItem(mediaId);
}