From 249a60b809eec400fe5b4a9b674f1dc43f4a2409 Mon Sep 17 00:00:00 2001 From: LorenzoJokhan Date: Fri, 19 Apr 2024 15:10:39 +0200 Subject: [PATCH] ResourceId gets properly set on extradata files url --- .../resource-form-widgets/lib/submit.js | 247 ++++++++++-------- 1 file changed, 131 insertions(+), 116 deletions(-) diff --git a/packages/cms/lib/modules/resource-form-widgets/lib/submit.js b/packages/cms/lib/modules/resource-form-widgets/lib/submit.js index b534c6736..074b25541 100644 --- a/packages/cms/lib/modules/resource-form-widgets/lib/submit.js +++ b/packages/cms/lib/modules/resource-form-widgets/lib/submit.js @@ -26,7 +26,6 @@ module.exports = async function (self, options) { const siteId = req.data.global.siteId; const postUrl = `${apiUrl}/api/site/${siteId}/${req.body.resourceEndPoint}`; - const getUrl = `${apiUrl}/api/site/${siteId}/${req.body.resourceEndPoint}/${req.body.resourceId}`; /** * Format headerr @@ -41,120 +40,124 @@ module.exports = async function (self, options) { const data = req.body; data.extraData = data.extraData ? data.extraData : {}; - if (req.files) { - const promises = []; - req.files.forEach((file, i) => { - const attachmentsPath = - 'public/uploads/attachments/resource-form-uploads/' + - req.body.resourceId; - - const nameHash = createHash('sha256') - .update(sessionSecret + Date.now().toString(), 'utf8') - .digest('hex'); - - const path = `${attachmentsPath}/${nameHash}`; - - if (fs.existsSync(attachmentsPath) === false) { - fs.mkdirSync(attachmentsPath, { recursive: true }); - } - - promises.push( - new Promise((resolve, reject) => { - const fileCopy = { name: file.originalname, url: path }; - // existing files are ignored; it is more then likely the same file - fs.access(path, fs.constants.F_OK, (err) => { - if (!err) { - return resolve(fileCopy); + const appendFilesToResource = async (resourceId) => { + const getUrl = `${apiUrl}/api/site/${siteId}/${req.body.resourceEndPoint}/${resourceId}`; + + if (req.files) { + const promises = []; + req.files.forEach((file, i) => { + const attachmentsPath = + 'public/uploads/attachments/resource-form-uploads/' + resourceId; + + const nameHash = createHash('sha256') + .update(sessionSecret + Date.now().toString(), 'utf8') + .digest('hex'); + + const path = `${attachmentsPath}/${nameHash}`; + + if (fs.existsSync(attachmentsPath) === false) { + fs.mkdirSync(attachmentsPath, { recursive: true }); + } + + promises.push( + new Promise((resolve, reject) => { + const fileCopy = { name: file.originalname, url: path }; + // existing files are ignored; it is more then likely the same file + fs.access(path, fs.constants.F_OK, (err) => { + if (!err) { + return resolve(fileCopy); + } + + fileType + .fromBuffer(file.buffer) + .then((type) => { + const isAllowed = [ + 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'application/vnd.ms-excel', + 'application/pdf', + 'application/msword', + 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', + '.docx', + '.doc', + 'application/vnd.ms-powerpoint', + 'application/vnd.openxmlformats-officedocument.presentationml.slideshow', + 'application/vnd.openxmlformats-officedocument.presentationml.presentation', + '.ppt', + '.pptx' + ].includes(type.mime); + + if (isAllowed) { + console.log('Create file', file.originalname); + fs.writeFile(path, file.buffer, (err) => { + err ? reject(err) : resolve(fileCopy); + }); + } else { + reject(new Error('File type not allowed')); + } + }) + .catch(() => reject(new Error('File type not allowed'))); + }); + }) + ); + }); + + try { + const results = await Promise.all(promises); + let files = results.map((file) => + Object.assign( + {}, + { + ...file, + url: file.url.replace('public', siteUrl), + date: Date.now(), + username: data.username, } - - fileType - .fromBuffer(file.buffer) - .then((type) => { - const isAllowed = [ - 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', - 'application/vnd.ms-excel', - 'application/pdf', - 'application/msword', - 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', - '.docx', - '.doc', - 'application/vnd.ms-powerpoint', - 'application/vnd.openxmlformats-officedocument.presentationml.slideshow', - 'application/vnd.openxmlformats-officedocument.presentationml.presentation', - '.ppt', - '.pptx' - ].includes(type.mime); - - if (isAllowed) { - console.log('Create file', file.originalname); - fs.writeFile(path, file.buffer, (err) => { - err ? reject(err) : resolve(fileCopy); - }); - } else { - reject(new Error('File type not allowed')); - } - }) - .catch(() => reject(new Error('File type not allowed'))); + ) + ); + + const httpHeaders = { + Accept: 'application/json', + 'Content-Type': 'application/json', + }; + + if (req.session.jwt) { + httpHeaders['X-Authorization'] = `Bearer ${req.session.jwt}`; + } + + if (resourceId) { + const response = await fetch(getUrl, { + headers: httpHeaders, }); - }) - ); - }); - - try { - const results = await Promise.all(promises); - let files = results.map((file) => - Object.assign( - {}, - { - ...file, - url: file.url.replace('public', siteUrl), - date: Date.now(), - username: data.username, - } - ) - ); - - const httpHeaders = { - Accept: 'application/json', - 'Content-Type': 'application/json', - }; - - if (req.session.jwt) { - httpHeaders['X-Authorization'] = `Bearer ${req.session.jwt}`; - } - - if (req.body.resourceId) { - const response = await fetch(getUrl, { - headers: httpHeaders, - }); - - if (response.ok) { - const idea = await response.json(); - - if (idea.extraData && idea.extraData.budgetDocuments) { - try { - const existingIdeaBudgets = JSON.parse( - idea.extraData.budgetDocuments - ); - files = files.concat(existingIdeaBudgets); - } catch (e) {} + + if (response.ok) { + const idea = await response.json(); + + if (idea.extraData && idea.extraData.budgetDocuments) { + try { + const existingIdeaBudgets = JSON.parse( + idea.extraData.budgetDocuments + ); + files = files.concat(existingIdeaBudgets); + } catch (e) {} + } } } + try { + data.extraData.budgetDocuments = JSON.stringify(files); + } catch (e) { + console.error('Budget documenten konden niet worden geupload'); + } + } catch (error) { + return res.status(400).send( + JSON.stringify({ + msg: error.message, + }) + ); } - try { - data.extraData.budgetDocuments = JSON.stringify(files); - } catch (e) { - console.error('Budget documenten konden niet worden geupload'); - } - } catch (error) { - return res.status(400).send( - JSON.stringify({ - msg: error.message, - }) - ); - } + } } + //format image if (data.image) { // when only one image filepondjs sadly just returns object, not array with one file, @@ -186,18 +189,30 @@ module.exports = async function (self, options) { delete data.extraData; } - const options = { - method: req.body.resourceId ? 'PUT' : 'POST', - uri: req.body.resourceId - ? `${postUrl}/${req.body.resourceId}` + if(req.body.resourceId) { + await appendFilesToResource(req.body.resourceId); + } + + const options = (resourceId) => ({ + method: resourceId ? 'PUT' : 'POST', + uri: resourceId + ? `${postUrl}/${resourceId}` : postUrl, headers: httpHeaders, body: data, json: true, // Automatically parses the JSON string in the response - }; - - rp(options) - .then(function (response) { + }); + + rp(options(req.body.resourceId)) + .then(async function (response) { + if(!req.body.resourceId) { + try { + await appendFilesToResource(response.id); + rp(options(response.id)); + } catch (err) { + console.log("Something went wrong while uploading the files") + } + } res.end( JSON.stringify({ id: response.id,