>>100565658
the removeImage function initiates a transaction and returns the successful result or an error if it fails
async removeImage(userId, imagePubId) {
try {
return MongooseRepository.initiateTransaction(async (session) => {
const user = await this.userRepository.findById(userId, { __v: 0 }, { lean: false }, session);
if (!user) {
return { success: false, body:' User not found' };
}
const image = await this.imageRepository.findOne({ publicId: imagePubId }, { __v: 0 }, {}, session);
if (!image) {
return { success: false, body: 'Image not found' };
}
user.photos.pull(image._id);
const response = await cloudinary.uploader.destroy(imagePubId, { resource_type: 'image', invalidate: true });
console.log(result)
if(response.result == 'ok'){
await this.userRepository.update(userId, user, { new: true }, session);
await this.imageRepository.delete(image._id, session);
return { success: true, body: result };
}else{
return { success: false, body: result };
}
});
} catch (e) {
return { success: false, body: e.message };
}
}
this is the transaction initiator:
async function initiateTransaction(fn) {
const session = await mongoose.startSession();
session.startTransaction();
try {
const result = await fn(session);
await session.commitTransaction();
return result;
} catch (error) {
await session.abortTransaction();
throw error;
} finally {
session.endSession();
}
}
is this too much spaghetti code?