const https = require('https'); const fs = require('fs-extra'); const path = require('path'); module.exports = Self => { Self.remoteMethod('downloadImages', { description: 'Returns last entries', accessType: 'WRITE', returns: { type: ['Object'], root: true }, http: { path: `/downloadImages`, verb: 'POST' } }); Self.downloadImages = async() => { const models = Self.app.models; try { const tempPath = path.join('/tmp/salix-image'); // Create temporary path await fs.mkdir(tempPath, {recursive: true}); const timer = setInterval(async() => { const image = await Self.findOne({where: {error: null}}); // Exit loop if (!image) return clearInterval(timer); const fileName = `${image.itemFk}.png`; const filePath = path.join(tempPath, fileName); const writeStream = fs.createWriteStream(filePath); writeStream.on('open', () => { https.get(image.url, async response => { if (response.statusCode != 200) { const error = new Error(`Could not download the image. Status code ${response.statusCode}`); return await errorHandler(image.itemFk, error, filePath); } response.pipe(writeStream); }).on('error', async error => { await errorHandler(image.itemFk, error, filePath); }); }); writeStream.on('error', async error => { await errorHandler(image.itemFk, error, filePath); }); writeStream.on('finish', async function() { try { await models.Image.registerImage('catalog', fileName, filePath); await image.destroy(); } catch (error) { await errorHandler(image.itemFk, error, filePath); } }); }, 2500); } catch (error) { throw new Error('Try-catch error: ', error); } async function errorHandler(rowId, error, filePath) { try { const row = await Self.findById(rowId); if (!row) throw new Error(`Could not update due error ${error}`); await row.updateAttribute('error', error); if (filePath && fs.existsSync(filePath)) await fs.unlink(filePath); } catch (error) { throw new Error('ErrorHandler error: ', error); } } }; };