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

57 lines
1.5 KiB
JavaScript
Raw Normal View History

2020-07-13 09:58:31 +00:00
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: {
2020-07-13 12:13:21 +00:00
type: ['Object'],
2020-07-13 09:58:31 +00:00
root: true
},
http: {
path: `/download`,
verb: 'GET'
}
});
Self.download = async() => {
const models = Self.app.models;
try {
2020-07-14 07:32:50 +00:00
const imageQueue = await Self.find({limit: 25});
const rootPath = models.Image.getPath();
2020-07-13 09:58:31 +00:00
const tempPath = path.join(rootPath, 'temp');
// Create temporary path
2020-07-13 12:31:50 +00:00
await fs.mkdir(tempPath, {recursive: true});
2020-07-13 09:58:31 +00:00
for (let image of imageQueue) {
2020-07-13 12:13:21 +00:00
const fileName = `${image.itemFk}.png`;
2020-07-14 07:32:50 +00:00
const filePath = path.join(tempPath, fileName);
const file = fs.createWriteStream(filePath);
2020-07-13 09:58:31 +00:00
https.get(image.url, async response => {
response.pipe(file);
2020-07-14 07:32:50 +00:00
});
2020-07-13 09:58:31 +00:00
2020-07-14 07:32:50 +00:00
file.on('finish', async function() {
await models.Image.registerImage('catalog', fileName, filePath);
2020-07-13 12:46:00 +00:00
await image.destroy();
2020-07-13 09:58:31 +00:00
});
2020-07-14 07:32:50 +00:00
file.on('error', err => {
fs.unlink(filePath);
throw err;
});
2020-07-13 09:58:31 +00:00
}
2020-07-13 12:22:19 +00:00
return imageQueue;
2020-07-13 09:58:31 +00:00
} catch (e) {
throw e;
}
};
};