@hv-kit/hexpress
Version:
facilitates typescript backend development with express
157 lines • 8.93 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.formidableUploadFile = exports.formidableFormData = exports.multerUploadForUpload = exports.multerUploadForExtract = void 0;
const hexpress_config_json_1 = __importDefault(require("../../../../hexpress.config.json"));
const formidable_1 = __importDefault(require("formidable"));
const path_1 = __importDefault(require("path"));
const fs_1 = __importDefault(require("fs"));
const error_1 = require("./error");
const other_1 = require("./other");
const file_1 = require("./file");
const string_1 = require("./string");
const multer = require('multer');
function multerUploadForExtract(dest = 'extract', configSUP = {}) {
configSUP = (typeof configSUP === 'object' &&
Array.isArray(configSUP)) ? configSUP : {};
const subPath = path_1.default.join(dest);
const uploadFolder = path_1.default.join(hexpress_config_json_1.default.server.static_rep, subPath);
(0, file_1.CreateDirectoryIfNotExists)(uploadFolder, false);
const multerDiskStorageForExtractSUB = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, uploadFolder);
}, filename: (req, file, cb) => {
cb(null, (0, string_1.RandomF)(10, 'alphanumeric_s', true, (data) => `temp_${data}_${(0, string_1.getAlphanumString)(file.originalname, '_')}`));
}, onError: function (err, next) {
if (hexpress_config_json_1.default.debug) {
console.log('----> uploads.ts > multerDiskStorageForExtract - err:: ', err);
}
next(err);
}
});
const multerUpload = multer(Object.assign(Object.assign({}, configSUP), { storage: multerDiskStorageForExtractSUB }));
return multerUpload;
}
exports.multerUploadForExtract = multerUploadForExtract;
function multerUploadForUpload(dest = 'upload', configSUP = {}) {
configSUP = (typeof configSUP === 'object' &&
Array.isArray(configSUP)) ? configSUP : {};
const subPath = path_1.default.join(dest);
const uploadFolder = path_1.default.join(hexpress_config_json_1.default.server.static_rep, subPath);
(0, file_1.CreateDirectoryIfNotExists)(uploadFolder, false);
const multerDiskStorageForUploadSUB = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, uploadFolder);
}, filename: (req, file, cb) => {
const filename = (0, string_1.RandomF)(10, 'alphanumeric_s', true, (data) => `${(0, string_1.getAlphanumString)(file.originalname, '_')}_${data}`);
const finaleFilename = [filename, (0, file_1.GetFileExtension)(file)].join('.');
cb(null, finaleFilename);
}, onError: function (err, next) {
if (hexpress_config_json_1.default.debug) {
console.log('----> uploads.ts > multerDiskStorageForUpload - err:: ', err);
}
next(err);
}
});
const multerUpload = multer(Object.assign(Object.assign({}, configSUP), { storage: multerDiskStorageForUploadSUB }));
return multerUpload;
}
exports.multerUploadForUpload = multerUploadForUpload;
function formidableFormData(dest = 'upload') {
function formidableFormDataMiddleware(req, res, next) {
return __awaiter(this, void 0, void 0, function* () {
let body = req.body;
body = (typeof body === 'object' &&
Array.isArray(body) === false) ? body : {};
let query = req.query;
query = (typeof query === 'object' &&
Array.isArray(query) === false) ? query : {};
const lang = query.lang;
try {
const subPath = path_1.default.join(dest);
const uploadFolder = path_1.default.join(hexpress_config_json_1.default.server.static_rep, subPath);
yield (0, file_1.CreateDirectoryIfNotExists)(uploadFolder, false);
const form = (0, formidable_1.default)({
multiples: true,
uploadDir: uploadFolder,
});
// console.log(`> src.scripts.uploads | formidableFormData <`);
// console.log(`> src.scripts.uploads | formidableFormData - uploadFolder:: `, uploadFolder);
form.parse(req, (err, fields, files) => __awaiter(this, void 0, void 0, function* () {
if (err) {
res.status(err.httpCode || 400).send((0, error_1.createStandardError)(hexpress_config_json_1.default.errors.invalid_form, (0, other_1.getLang)(lang), err).res);
return;
}
files = (typeof files === 'object' &&
Array.isArray(files) === false) ? files : {};
req.body = Object.assign(Object.assign(Object.assign({}, body), fields), files);
// const file = files.file;
/* const isValid = JON.Validator.isValid(
new JON.File(lang).required().changeFileType(formidable.PersistentFile).length(115692),
file,
); */
// const newName: string = await formidableUploadFile(file, subPath, getLang(lang));
// console.log(`> src.scripts.uploads | formidableFormData - file.originalFilename:: `, file.originalFilename);
// console.log(`> src.scripts.uploads | formidableFormData - files:: `, files);
// console.log(`> src.scripts.uploads | formidableFormData - isValid:: `, isValid);
// console.log(`> src.scripts.uploads | formidableFormData - newName:: `, newName);
next();
}));
}
catch (error) {
res.status(400).send((0, error_1.createStandardError)(hexpress_config_json_1.default.errors.invalid_form, (0, other_1.getLang)(lang), error).res);
}
});
}
;
return formidableFormDataMiddleware;
}
exports.formidableFormData = formidableFormData;
function formidableUploadFile(file, uploadFolder, lang = 'fr') {
return __awaiter(this, void 0, void 0, function* () {
try {
const arrayFilename = file.originalFilename.split('.');
const filename = arrayFilename[0];
const extension = arrayFilename.reverse()[0];
const finalFilename = (0, string_1.RandomF)(20, 'alphanumeric', true, (data) => `${(0, string_1.getAlphanumString)(filename, '_')}.${data}.${extension}`);
const subPath = path_1.default.join(uploadFolder, finalFilename);
const finalDirPath = path_1.default.join(hexpress_config_json_1.default.server.static_rep, uploadFolder);
yield (0, file_1.CreateDirectoryIfNotExists)(finalDirPath, false);
// console.log(`> src.scripts.uploads | formidableUploadFile - finalFilename:: `, finalFilename);
// console.log(`> src.scripts.uploads | formidableUploadFile - file.filepath:: `, file.filepath);
fs_1.default.renameSync(file.filepath, path_1.default.join(hexpress_config_json_1.default.server.static_rep, subPath));
if (fs_1.default.existsSync(file.filepath)) {
fs_1.default.unlinkSync(file.filepath);
}
return subPath;
}
catch (error) {
const err = (0, error_1.createStandardError)(hexpress_config_json_1.default.errors.unknown_error, (0, other_1.getLang)(lang), error);
if (file && file.filepath) {
if (fs_1.default.existsSync(file.filepath)) {
fs_1.default.unlinkSync(file.filepath);
}
}
throw err;
}
});
}
exports.formidableUploadFile = formidableUploadFile;
exports.default = {
multerUploadForExtract,
multerUploadForUpload,
formidableFormData,
formidableUploadFile,
};
//# sourceMappingURL=upload.js.map