@jrmc/adonis-attachment
Version:
Turn any field on your Lucid model to an attachment data type
60 lines (59 loc) • 2.21 kB
JavaScript
/**
* @jrmc/adonis-attachment
*
* @license MIT
* @copyright Jeremy Chaufourier <jeremy@chaufourier.fr>
*/
import logger from '@adonisjs/core/services/logger';
import VariantGeneratorService from './variant/variant_generator_service.js';
import VariantPurgerService from './variant/variant_purger_service.js';
import VariantPersisterService from './variant/variant_persister_service.js';
export default class VariantService {
#record;
#attributeName;
#options;
#filters;
#variantGenerator;
#variantPurger;
#variantPersister;
constructor({ record, attributeName, options, filters }) {
this.#record = record;
this.#attributeName = attributeName;
this.#options = options;
this.#filters = filters;
this.#variantGenerator = new VariantGeneratorService();
this.#variantPurger = new VariantPurgerService(filters);
this.#variantPersister = new VariantPersisterService({
id: record.row.$primaryKeyValue?.toString() || record.row.$attributes['id'],
modelTable: record.row.constructor.table,
attributeName,
multiple: Array.isArray(record.row.$original[attributeName]),
primaryKey: record.row.constructor.primaryKey ?? 'id'
});
}
async run() {
try {
const attachments = await this.#getAttachments();
if (!this.#shouldProcess(attachments)) {
return;
}
await this.#variantPurger.purge(attachments);
const variants = await this.#variantGenerator.generate({ attachments, options: this.#options, filters: this.#filters });
await this.#variantPersister.persist({ attachments, variants });
return variants;
}
catch (error) {
logger.error(`VariantService.run failed: ${error.message}`);
throw error;
}
}
async #getAttachments() {
// await this.#record.row.refresh()
return this.#record.getAttachments({
attributeName: this.#attributeName,
});
}
#shouldProcess(attachments) {
return !!(attachments?.length && this.#options?.variants?.length);
}
}