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'); */ const rootPath = models.Image.getPath(); const tempPath = path.join(rootPath, 'temp'); // 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); } }); }, 1000); } catch (error) { await errorHandler(image.itemFk, error); } async function errorHandler(rowId, error, filePath) { const row = await Self.findById(rowId); await row.updateAttribute('error', error); if (filePath) await fs.unlink(filePath); } }; };