@tasolutions/express-core
Version:
All libs for express
83 lines (76 loc) • 3.82 kB
JavaScript
const _ = require('lodash');
const stringHelper = require('./string.helper');
const { validate, upload } = require('./s3Upload');
const { uploadInfo } = require('../config');
module.exports = {
/**
* This function upload file
*/
uploadFiles: async (req, Collection, type = uploadInfo.type) => {
const collectionName = Collection.collection.collectionName;
const folder = collectionName ? `${collectionName}` : '';
await Promise.all(
_.map(_.keysIn(req.files), async (key) => {
let field_data = req.files[key];
const path = Collection.schema.path(key);
const isInstance = path.instance;
// check files is array or object
if (field_data) {
if (_.isArray(field_data)) {
// insert multiple images
let data = [];
// loop all files
await Promise.all(
_.map(_.keysIn(field_data), async (key) => {
let photo = field_data[key];
if (!photo || photo.size === 0) {
throw new Error(`File ${photo.name} is invalid or empty.`);
}
let file_name = `${folder}/${stringHelper.randomImageName()}-${photo.name}`;
if (type === 'S3') {
photo.folder_path = folder;
let { data } = await validate(photo);
const uploadRes = await upload(data);
file_name = uploadRes.Location;
} else {
photo.mv(`./uploads/${file_name}`);
}
data.push(file_name);
})
);
// req.body[key] = data;
if (isInstance == 'Array') {
req.body[`${key}`] = req.body[`${key}`] ? req.body[`${key}`] : [];
req.body[`${key}`] = req.body[`${key}`].concat(data);
} else {
req.body[`${key}`] = data;
}
} else {
if (field_data.size === 0) {
throw new Error(`File ${field_data.name} is invalid or empty.`);
}
// insert one image
let file_name = `${folder}/${stringHelper.randomImageName()}-${field_data.name}`;
if (type === 'S3') {
field_data.folder_path = folder;
let { data } = await validate(field_data);
const uploadRes = await upload(data);
file_name = uploadRes.Location;
} else {
field_data.mv(`./uploads/${file_name}`);
}
// req.body[key] = file_name;
if (isInstance == 'Array') {
req.body[`${key}`] = req.body[`${key}`] ? _.isArray(req.body[`${key}`]) ? req.body[`${key}`] : [req.body[`${key}`]] : [];
req.body[`${key}`].push(file_name);
} else {
req.body[`${key}`] = file_name;
req.body[`${key}_name`] = field_data.name;
}
}
}
})
);
return req.body;
}
}