@jrmc/adonis-attachment
Version:
Turn any field on your Lucid model to an attachment data type
47 lines (46 loc) • 1.59 kB
JavaScript
/**
* @jrmc/adonis-attachment
*
* @license MIT
* @copyright Jeremy Chaufourier <jeremy@chaufourier.fr>
*/
import attachmentManager from '../../../services/main.js';
export class AttachmentTransactionService {
/**
* During commit, we should cleanup the old detached files
*/
async commit(detachedAttachments) {
await Promise.allSettled(detachedAttachments.map((attachment) => attachmentManager.remove(attachment)));
}
/**
* During rollback we should remove the attached files.
*/
async rollback(attachedAttachments) {
await Promise.allSettled(attachedAttachments.map(async (attachment) => {
await attachment.rollbackMoveFileForDelete();
await attachmentManager.remove(attachment);
}));
}
/**
* Handle transaction lifecycle with commit and rollback hooks
*/
async handleTransaction(record, options = { enabledRollback: true }) {
try {
if (record.row.$trx) {
record.row.$trx.after('commit', () => this.commit(record.row.$attachments.detached));
if (options.enabledRollback) {
record.row.$trx.after('rollback', () => this.rollback(record.row.$attachments.attached));
}
}
else {
await this.commit(record.row.$attachments.detached);
}
}
catch (error) {
if (options.enabledRollback) {
await this.rollback(record.row.$attachments.attached);
}
throw error;
}
}
}