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({limit: 25}); const rootPath = models.Image.getPath(); const tempPath = path.join(rootPath, 'temp'); // 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 => { response.pipe(file); }); file.on('finish', async function() { await models.Image.registerImage('catalog', fileName, filePath); await image.destroy(); }); file.on('error', err => { fs.unlink(filePath); throw err; }); } return imageQueue; } catch (e) { throw e; } }; };