How save multiple values JSONStore - save

I need to replace multiple value in JSONStore of IBM Worklight.
In this way is saved only first value. Why?
.then(function() {
for (var index = 0; index < elencoSpese.length; index++) {
var spesa = elencoSpese[index];
var spesaReplace = {_id: spesa.id, json: spesa};
spesa.id_nota_spesa = idNotaSpesa;
spesa.checked = true;
WL.JSONStore.get(COLLECTION_NAME_SPESE).replace(spesaReplace);
}
})

You want to build an array of JSONStore documents and pass it to the replaceAPI. For example:
.then(function() {
var replacementsArray = [];
for (var index = 0; index < elencoSpese.length; index++) {
var spesa = elencoSpese[index];
var spesaReplace = {_id: spesa.id, json: spesa};
spesa.id_nota_spesa = idNotaSpesa;
spesa.checked = true;
replacementsArray.push(spesaReplace);
}
return WL.JSONStore.get(COLLECTION_NAME_SPESE).replace(replacementsArray);
})
.then(function (numOfDocsReplaced) {
// numOfDocsReplaced should equal elencoSpese.length
})
I assume this happens in the JavaScript implementation of the JSONStore API, if that's the case the answer is in the documentation here. The JavaScript implementation of JSONStore expects code to be called serially. Wait for an operation to finish before you call the next one. When you call the replace multiple times without waiting, you're calling the API in parallel instead of serially. This should not be an issue in the production environments (i.e. Android, iOS, WP8 and W8).

Related

Graph API: What is the correct way to interrupt Pagination

I am using this script to fetch Chats. I need 100 chats maximum but it may happen that a chat do not have 100 messages. How can I handle that case in this script?
I am using Node Package Microsoft Graph Client.
const { Client, PageIterator } = require('#microsoft/microsoft-graph-client');
async getChatList(GroupChatId) {
let messages = [];
let count = 0;
let pauseAfter = 100; // 100 messages limit
let response = await this.graphClient
.api(`/chats/${GroupChatId}/messages`)
.version('beta')
.get();
let callback = (data) => {
messages.push(data);
count++;
return count < pauseAfter;
}
let pageIterator = new PageIterator(this.graphClient, response, callback);
await pageIterator.iterate();
return messages;
}
As I answered on the GitHub issue you opened, the iterator should stop all by itself if it runs out of items to iterate before hitting your "maximum". However, I think you're hitting a bug in the specific API you're using /chats/id/messages.
The problem is that this API is returning a nextLink value in it's response even if there are no next pages. It shouldn't be, and I'm reporting that to the Teams folks. That's causing the pageIterator to try to get the next set of results, which returns 0 items and a nextLink. You're stuck in an infinite loop.
So because of this, using the pageIterator just won't work for this API. You'll need to do the iteration yourself. Here's some TypeScript code to show it:
let keepGoing: Boolean = true;
do
{
// If there are no items in the page, then stop
// iterating.
keepGoing = currentPage.value.length > 0;
// Loop through the current page
currentPage.value.forEach((message) => {
console.log(JSON.stringify(message.id));
});
// If there's a next link follow it
if (keepGoing && !isNullOrUndefined(currentPage["#odata.nextLink"]))
{
currentPage = await client
.api(currentPage["#odata.nextLink"])
.get();
}
} while (keepGoing);
You need to check with a conditional statement if the message has value or not.
The pseudo code is given below:
let callback = (data) => {
if(data != "" || data != null)
{
messages.push(data);
count++;
return count < pauseAfter;
}
else{
return;
}
}

Looping through custom fields to populate dynamic fields in Zapier

I'm not sure how to loop through the custom fields when adding a dynamic field via the web script editor.
When I test I can see the fields are being returned in the console
Where the number of fields is different with each instance of our app.
This is the code I'm using to return the data.
return z.request(options)
.then((response) => {
response.throwForStatus();
const results = z.JSON.parse(response.content)._embedded;
return results;
});
I assume I need to loop through each of the fields, pull out the ID and name and then put them back as an array of objects?
Something like this, only problem is nothing is being returned?
return z.request(options)
.then((response) => {
response.throwForStatus();
const results = z.JSON.parse(response.content).results._embedded;
var cFields = [];
for (var i = 0; i < results.length; i++) {
cFields.push({'id': results.customFields[i].label});
}
return cFields;
});
Any pointers?
I worked this out in the end. I think the problem was more because of my lack of coding knowledge. Not sure if this is the best answer but it worked.
return z.request(options)
.then((response) => {
response.throwForStatus();
const results = z.JSON.parse(response.content)._embedded;
let customFields = [];
for (let i = 0; i < results.customFields.length; i++) {
let customFieldsObj = {};
customFieldsObj['key'] = results.customFields[i].id;
customFieldsObj['label'] = results.customFields[i].label;
let helpText = results.customFields[i].type + ' Field';
customFieldsObj['helpText'] = helpText.toUpperCase();
customFields.push(customFieldsObj);
}
return customFields;
});

sapui5 batch with sap.ui.model.odata.v2.ODataModel

I created table with data using JSONModel
var oModel = new sap.ui.model.json.JSONModel(query);
oTablePrio = sap.ui.getCore().getControl("idTablePrio2");
oTablePrio.setModel(oModel, "Prio2");
Everythink look and work good.
Now i have added new column(prio) where i will change value. After changing i would like to save every rows( in the SAP ztable ) after clicking buton save .
I made something like this
var oModel = new sap.ui.model.odata.v2.ODataModel(gServiceUrl);
oModel.setUseBatch(true);
for (var i = 0; i < data.length; i++) {
sEntry.Matnr = data[i].Matnr;
sEntry.Bbynr = data[i].Bbynr;
sEntry.Prio = data[i].Prio;
oModel.update("/WielosztSet('"+data[i].Bbynr+"')", sEntry, {
method: "PUT", function(){
alert('Data Updated Successfully');
location.reload(true);
},function(){
sap.m.MessageToast.show('Update failed',{duration:1000});
}});
}
Now only it sends data only with the last row.
I wrote that i cannot update more than one row in this way and I need to make batch.
I connot find how to create working batch for uploding data with sap.ui.model.odata.v2.ODataModel
Please give me some advice.
Before the call of the oModel.update assign the UseBatch to true:
oModel.setUseBatch(true);
Make your for:
for (var i = 0; i < data.length; i++) {
sEntry.Matnr = data[i].Matnr;
sEntry.Bbynr = data[i].Bbynr;
sEntry.Prio = data[i].Prio;
oModel.update("/WielosztSet('"+data[i].Bbynr+"')", sEntry, {
method: "PUT", function(){
alert('Data Updated Successfully');
location.reload(true);
},function(){
sap.m.MessageToast.show('Update failed',{duration:1000});
}});
}
At the end of for put the submitChanges.
oModel.submitChanges();
oModel.setUseBatch(false); // Make false if you reuse this oModel.
Regards.

Using fetch in a loop in code by zapier

I want to do 3 different api call from my zapier code, get their returns in variables and merge them. I can't figure out how to do that. It will be like:
var urls = [apiUrl1, apiUrl2, apiUrl3];
var output = [];
for ( i = 0; i < urls.length; i++ ) {
output[i] = fetch( urls[i] );
}
This is an example code. I can't get response to output, it gets only a blank object {}. What will be the procedure to save the fetch return values in the output array?
Since apparently the folks at Zapier do not like to give out working examples or any sort of decent documentation for this level of code intricacy... here is a working example:
var promises = [];
for (var i = urls.length - 1; i >= 0; i--) {
promises.push(fetch(urls[i]));
}
Promise.all(promises).then(function(res){
var blobPromises = [];
for (var i = res.length - 1; i >= 0; i--) {
blobPromises.push(res[i].text());
}
return Promise.all(blobPromises);
}).then(function(body){
var output = {id: 1234, rawData: body};
callback(null, output);
}).catch(callback);
This may not be the cleanest solution, but it works for me. Cheers!
Two things you'll need to brush up on:
Promises - especially Promise.all() - there is lots out there about that.
Callback to return the data asynchronously. Our help docs describe this.
The main reason your code fails is because you are assuming the fetch happens immediately. In JavaScript that is not the case - it happens Async and you have to use promises and callbacks to wait until they are done before returning the output via the callback!

q promise and map doesn't change after iteration

I'm using Q Promises to retrieve data from my redis repository. The problem I'm having, is that through each iteration, the array object (localEncounter) I'm using to store data returned from the chained functions is never updated at each iteration. Previously, I tried to solve this with a foreach loop and spread but the results were the same.
How should I correct this so that localEncounter is updated at each iteration, and ultimately localEncounters contains correct data when returned? Thank you.
var localEncounters = [];
var localEncounter = {};
Promise.all(ids.map(function(id) {
return localEncounter, getEncounter(id, client)
.then(function (encounter) {
encounterObject = encounter;
//set the fields for the return object
localEncounter['encounterid'] = encounterObject[f_id];
localEncounter['screeningid'] = encounterObject[f_screening_id];
localEncounter['assessmentid'] = encounterObject[f_clinical_assessment_id];
localEncounter['psychevalid'] = encounterObject[f_psych_eval_id];
//get screening
return getScreening(encounterObject[f_screening_id], client);
})
.then(function (screening) {
//set the fields for the return object
localEncounter['screeningbegintime'] = screening[f_begin_time];
//get assessment
return getAssessment(localEncounter['assessmentid'], client);
})
.then(function (assessment) {
//set the fields for the return object
localEncounter['assessmentbegintime'] = assessment[f_begin_time];
//get psycheval
//localEncounters.push(assessment);
return getPsychEval(localEncounter['psychevalid'], client);
})
.then(function (psychEval) {
//set the fields for the return object
localEncounter['assessmentbegintime'] = psychEval[f_begin_time];
localEncounters.push(localEncounter);
}
, function (reason) {
console.log(reason); // display reason why the call failed;
reject(reason, 'Something went wrong creating the encounter!');
})
})).then(function(results) {
// results is an array of names
console.log('done ');
resolve(localEncounters);
})
Solution: I only needed to move the declaration of localEncounter inside the map iterator
before:
var localEncounter = {};
Promise.all(ids.map(function(id) {
after:
Promise.all(ids.map(function(id) {
var localEncounter = {};
This now allows that each id iteration gets its own localEncounter object.

Resources