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 imageQueue = await Self.find({where: {error: null}}); const tempPath = path.join('/tmp/salix-image'); // Create temporary path await fs.mkdir(tempPath, {recursive: true}); for (let image of imageQueue) { const fileName = `${image.itemFk}.png`; const filePath = path.join(tempPath, fileName); const file = fs.createWriteStream(filePath); https.get(image.url, async response => { if (response.statusCode != 200) { const error = new Error(`Could not download the image. Status code ${response.statusCode}`); file.close(); await errorHandler(image.itemFk, error, filePath); } response.pipe(file); file.on('error', async error => { await errorHandler(image.itemFk, error, filePath); }); file.on('finish', async function() { try { await models.Image.registerImage('catalog', fileName, filePath); await image.destroy(); } catch (error) { await errorHandler(image.itemFk, error, filePath); } }); }).on('error', async error => { await errorHandler(image.itemFk, error, filePath); }); } return imageQueue; } 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); } }; };