Skip to content

Commit

Permalink
Merge pull request #450 from openstad/bugfix/undefined-resourceid-whe…
Browse files Browse the repository at this point in the history
…n-saving-files-on-new-resource

ResourceId gets properly set on extradata files url
  • Loading branch information
rudivanhierden committed Apr 22, 2024
2 parents e7df85e + 249a60b commit 82025f9
Showing 1 changed file with 131 additions and 116 deletions.
247 changes: 131 additions & 116 deletions packages/cms/lib/modules/resource-form-widgets/lib/submit.js
Expand Up @@ -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
Expand All @@ -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,
Expand Down Expand Up @@ -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,
Expand Down

1 comment on commit 82025f9

@github-actions
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Published new image: openstad/frontend:development-82025f9

Please sign in to comment.