I am using the fetch API to make a RESTfull request to an API endpoint that returns a response with data that I need to iterate over and update properties on the response, after converting to a JSON object. I need the function that updates the properties to complete before passing the new object to a “POST” request to create a new asset on the server based on the new object. Currently, with the code below, I am getting a stack overflow error with the function “getUpdatedBody”, I am sure it has to do with the nature of using Promises with a recursive function. Could someone look this over and let me know if something is incorrect with my syntax or if there is a better way to accomplish this? Thanks!
fetch("http://<my uri>/api/v1/read/page/<site name>/_prototypes/events/event?<credentials>"
)
.then(r => r.json())
.then(data => {
if(data.success) {
const currentBody = data.asset;
const getUpdatedBody = async () => {
for(const prop in currentBody) {
return new Promise( async (resolve, reject) => {
if (typeof currentBody[prop] === 'object' && prop != 'structuredDataNodes') {
await getUpdatedBody(currentBody[prop]);
} else
if(prop['body-text']) {
prop['body-text'] = 'Body text from API';
} else
if(prop['start']) {
prop['start'] = '1478059200000';
} else
if(prop === 'name') {
prop.name = 'New event from API';
} else
if(prop === 'parentFolderPath') {
prop.parentFolderPath = 'news/events/2020/10'
}
});
}
}
getUpdatedBody().then(newBody => {
fetch("http:<my uri>/api/v1/create?<credentials>", {
method: 'POST',
body: JSON.stringify(newBody)
})
.then(r => r.json())
.then(data2 => {
if (data2.success)
console.log('Success');
else
console.log('Error occurred when issuing an edit: ' + data.message);
});
});
} else {
console.log('Error occurred when issuing a read: ' + data.message);
}
});