salix/modules/item/back/methods/item-image-queue/download.js

57 lines
1.5 KiB
JavaScript

const https = require('https');
const fs = require('fs-extra');
const path = require('path');
module.exports = Self => {
Self.remoteMethod('download', {
description: 'Returns last entries',
accessType: 'WRITE',
returns: {
type: ['Object'],
root: true
},
http: {
path: `/download`,
verb: 'GET'
}
});
Self.download = 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;
}
};
};