Not sure this is correct as it moves additionalScope into the onFailure, whereas they are used to send to juggleEnergyAPI. And they seem to work fine not as key value pairs. I'll test and send them as key value pairs if works as its probably neater.
I have worked out the issue with the API onSuccess: it just didn't like startDate & endDate, removing them allowed it to write the text. Altering it to onSuccess: (results) => { console.log("API Success: " + results[0].date_time + " " + results[results.length-1].date_time); return true; },
seemed to make it happy.
I am now returning results from API call to {{dynamic_data}}
and sending that as additional scope to upsertHistory (as a Key value pair). Which is probable slicker.
Removing the await on upsertHistory messes up the console logs using startDate & endDate as they get out of sync. But now I can follow them all through I'll most likely comment out some of the logs. The upsert comments are not true reflections as they just repeat the startDate & endDate, but it doesn't return the data, just a confirmation of 'Bulk Upsert by Key'. But testing by tweaking vlaues already stored proves it works.
async function runJuggleEnergyAPI() {
const weeks = meterHistoryRequired.value
const emigId = meterList.selectedRow.emigId;
let initialEndDate = moment().startOf('day').format('YYYYMMDD');
let initialStartDate = moment(initialEndDate).add(-7, 'days').format('YYYYMMDD');
var startDate;
var endDate;
for (let weeksAgo = 0; weeksAgo < weeks; weeksAgo++) {
startDate = moment(initialStartDate).add(-weeksAgo, 'weeks').format('YYYYMMDD')
endDate = moment(initialEndDate).add(-weeksAgo, 'weeks').format('YYYYMMDD')
console.log("Next API Call:" + startDate + " " + endDate)
let dynamic_data = await juggleEnergyAPI.trigger({
onSuccess: (results) => {
console.log("API Success: " + results[0].date_time + " " + results[results.length-1].date_time);
return true;
},
onFailure: (error) => {
console.error(error);
return false;
},
additionalScope: { emigId, startDate, endDate }
});
await upsertHistory3.trigger({
onSuccess: () => {console.log("Upsert Success: " + startDate + " " + endDate);},
onFailure: () => {console.log("Upsert Fail: " + startDate + " " + endDate);},
additionalScope: {dynamic_data: dynamic_data}
})
console.log("EndLog:" + dynamic_data[0].date_time + " " + dynamic_data[dynamic_data.length-1].date_time)
// console.log("lastRead: " + dynamic_data[dynamic_data.length-1].date_time)
}
}
return runJuggleEnergyAPI();
But all working, and technique improved by returning the API data to the JS script.
Comments welcome
Dave