const fs = require('fs-extra'); const sharp = require('sharp'); const path = require('path'); module.exports = Self => { require('../methods/image/download')(Self); require('../methods/image/upload')(Self); Self.registerImage = async(collectionName, srcFile, entityId) => { const models = Self.app.models; const tx = await Self.beginTransaction({}); const myOptions = {transaction: tx}; try { const collection = await models.ImageCollection.findOne({ fields: [ 'id', 'name', 'maxWidth', 'maxHeight', 'model', 'property' ], where: {name: collectionName}, include: { relation: 'sizes', scope: { fields: ['width', 'height', 'crop'] } } }, myOptions); const file = srcFile.split('/').pop(); const fileName = file.split('.')[0]; const data = { name: fileName, collectionFk: collectionName }; const newImage = await Self.upsertWithWhere(data, { name: fileName, collectionFk: collectionName, updated: (new Date).getTime() }, myOptions); // Resizes and saves the image const container = await models.ImageContainer.getContainer(collectionName); const rootPath = container.client.root; const collectionDir = path.join(rootPath, collectionName); const dstDir = path.join(collectionDir, 'full'); const dstFile = path.join(dstDir, file); const resizeOpts = { withoutEnlargement: true, fit: 'inside' }; await fs.mkdir(dstDir, {recursive: true}); await sharp(srcFile, {failOnError: false}) .resize(collection.maxWidth, collection.maxHeight, resizeOpts) .png() .toFile(dstFile); const sizes = collection.sizes(); for (let size of sizes) { const dstDir = path.join(collectionDir, `${size.width}x${size.height}`); const dstFile = path.join(dstDir, file); const resizeOpts = { withoutEnlargement: true, fit: size.crop ? 'cover' : 'inside' }; await fs.mkdir(dstDir, {recursive: true}); await sharp(srcFile, {failOnError: false}) .resize(size.width, size.height, resizeOpts) .png() .toFile(dstFile); } const model = models[collection.model]; if (!model) throw new Error('Matching model not found'); const item = await model.findById(entityId, null, myOptions); if (item) { await item.updateAttribute( collection.property, fileName, myOptions ); } if (fs.existsSync(srcFile)) await fs.unlink(srcFile); await tx.commit(); return newImage; } catch (e) { await tx.rollback(); throw e; } }; };