UNPKG

formflux

Version:

A package to upload files to a server and parsing multipart-formData requests

98 lines (97 loc) 3.23 kB
import createNewBody from "./helpers/resBodyMaker"; import EventHandlers from "./EventHandlers"; class setFileNameToBody { constructor(obj) { this.obj = void 0; this.obj = obj; } setFileNames(req) { try { req.body = req.body ? req.body : {}; for (let i = 0; i < this.obj.metaData.length; i++) { if (this.obj.fileName.length > 0) { if (/\[.*\]/.test(this.obj.fieldNameFile[i])) { this.nestedData(req, this.obj.fieldNameFile[i], this.obj.fileName[i]); } if (!req.body[`${this.obj.fieldNameFile[i]}`] && !/\[.*\]/.test(this.obj.fieldNameFile[i])) req.body[`${this.obj.fieldNameFile[i]}`] = this.obj.modifiedFileName[i];else if (req.body[`${this.obj.fieldNameFile[i]}`] && !/\[.*\]/.test(this.obj.fieldNameFile[i])) req.body[`${this.obj.fieldNameFile[i]}`] = [req.body[`${this.obj.fieldNameFile[i]}`], this.obj.modifiedFileName[i]].flat(); } } } catch (err) { console.log(err); EventHandlers.emit("parseError", { message: "Error in parsing form data.Invalid Format!", code: 400 }); } } nestedData(req, fieldName, data) { let outer = fieldName.substring(0, fieldName.indexOf("[")); let inners = fieldName.substring(fieldName.indexOf("[")); let i = 0; let current; let prev; let temp = inners.match(/\[([^\]]+)\]/g).map(s => s.slice(1, -1)); // [a,b,c] => [a,b,c] if (!req.body[`${outer}`]) { for (let _i = temp.length - 1; _i >= 0; _i--) { if (!isNaN(temp[_i])) { if (!prev) { current = [data]; prev = current; } else { current = [prev]; prev = current; } } else { if (!prev) { current = { [`${temp[_i]}`]: data }; prev = current; } else { current = { [`${temp[_i]}`]: prev }; prev = current; } } } req.body[`${outer}`] = current; } else { temp.unshift(outer); this.getNestedField(req, req.body, temp, temp[temp.length - 1], data, 0, req.body); } } // mapping..... getNestedField(req, obj, posArr, keySearch, data, i, prevObj) { if (i == posArr.length - 1) { // reached last position set the value if (Array.isArray(obj)) { if (!isNaN(posArr[i])) { // if the current position is a number then it is an array obj[posArr[i]] ? obj[posArr[i]] = data : obj.push(data); return; } else { obj[posArr[i]] = data; // needs some checking return; } } else { // it is an objct obj[posArr[i]] = data; return; } } if (!obj[posArr[i]]) { if (!isNaN(posArr[i])) { obj[posArr[i]] = createNewBody(posArr, i + 1, data); // create the rest return; } else { obj[posArr[i]] = createNewBody(posArr, i + 1, data); return; } } prevObj = obj[posArr[i]]; this.getNestedField(req, obj[posArr[i]], posArr, keySearch, data, i + 1, prevObj); } } export default setFileNameToBody; //# sourceMappingURL=setFileNameToBody.js.map