diff --git a/modules/item/back/methods/item-image-queue/downloadImages.js b/modules/item/back/methods/item-image-queue/downloadImages.js index 372648dd6c..c7054b3400 100644 --- a/modules/item/back/methods/item-image-queue/downloadImages.js +++ b/modules/item/back/methods/item-image-queue/downloadImages.js @@ -20,9 +20,8 @@ module.exports = Self => { const models = Self.app.models; try { - const imageQueue = await Self.find({limit: 25}); - const rootPath = models.Image.getPath(); - const tempPath = path.join(rootPath, 'temp'); + const imageQueue = await Self.find({where: {error: null}}); + const tempPath = path.join('/temp/salix-image'); // Create temporary path await fs.mkdir(tempPath, {recursive: true}); @@ -33,24 +32,43 @@ module.exports = Self => { 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('finish', async function() { - await models.Image.registerImage('catalog', fileName, filePath); - await image.destroy(); - }); + file.on('error', async error => { + await errorHandler(image.itemFk, error, filePath); + }); - file.on('error', err => { - fs.unlink(filePath); - - throw err; + 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 (e) { - throw e; + } 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); } }; }; diff --git a/modules/item/back/models/item-image-queue.json b/modules/item/back/models/item-image-queue.json index 61cb7b0180..6e248ac96d 100644 --- a/modules/item/back/models/item-image-queue.json +++ b/modules/item/back/models/item-image-queue.json @@ -16,6 +16,10 @@ "url": { "type": "String", "required": true + }, + "error": { + "type": "String", + "required": true } }, "relations": {