parse.com cloud code, getting cloud code to see variables - javascript

I have Cloud Code I am having trouble linking together... I have been able to utilize Parse effectively for the iOS side on a separate app. I have basic JS skills, throwing the custom Cloud Code in the mix is mucking things up for me. I have read their documentation, and searched for other examples, it is not clicking.
The first function finds objects that meets certain parameters... Works fine.
Parse.Cloud.job("callClient", function(request, response){
var now = new Date();
var message = Parse.Object.extend("Message");
var query = new Parse.Query(message);
query.greaterThan("alertDate", now);
query.find({
success: function(results){
for (var i = 0; i < results.length; i++){
var alertDate = results[i].get("alertDate"); // <- for testing, working
var toPhone = results[i].get("toPhone"); // <- for testing, working
console.log("This is inline- Item number: "+ (i+1) + " Alert date is: " + alertDate + "To Phone: "+ toPhone);
var caller = results[i];
Parse.Cloud.run("testCall",function(request, response) {
}); // <- will fire with with default info
}
response.success("function complete");
}
})
});
The second function is a Twilio feature inside Parse, which also works fine...
Parse.Cloud.define("testCall", function(request, response) {
var client = require('twilio')('Acct SID','Auth Code');
Parse.Cloud.useMasterKey();
client.makeCall({
to:'+17205551212',
from:'+17205551213',
url:'http://TWIml-File.xml',
method:'GET'
}, function(err, responseData){
if (err){
response.error("fail");
}else{
response.success("success");
}
});
});
I realize I cannot pass an object to a cloud code function, nor does a global variable persist. So how do I get the results of "callClient" visible to "testCall"?

According to the Parse staff, it is not possible to maintain a global state across different cloud module sessions.
I run into a similar issue, and I have decided to follow their tip.
Parse cloud javascript global variable

Problem solved...
I was depending too much on the cloud code itself. I thought I needed it for all the functions I was trying to do, based on what I interpreted in the documentation.
I discarded "testCall" as a cloud code function, and made it a regular JS function, and embedded the other stuff inside it and works great.

Related

javascript Firebase database get values grouped

I need these values in a row, but I don't want them reply if its already in div.
My try is here. I try to build an array and put these values from firebase to here, but still I can't see in html.
var fruits = [];
var fetchPostsleft = function(postsRef, sectionElement,fruits) {
postsRef .orderByChild('timeStamp').on('child_added', function(data) {
console.log(data.val());
var author = data.val().senderName;
var containerElement2 = sectionElement.getElementsByClassName('posts-containerleft')[0];
fruits.push(data.val().senderName);
console.log(fruits.length);
});
};
fetchPostsleft(topUserPostsRef, topUserPostsSectionleft,fruits);
var fLen = fruits.length;
console.log(fruits.length);
for (var i = 0; i < fLen; i++) {
// text += "<li>" + fruits[i] + "</li>";
topUserPostsSectionleft.getElementsByClassName('posts-containerleft')[0].insertBefore( createheaders(fruits[i], ""),
topUserPostsSectionleft.getElementsByClassName('posts-containerleft')[0].firstChild);
}
The data is loaded from Firebase asynchronously. This means that by the time your looping over the array, it hasn't been populated yet. It's easiest to see this by replacing most of the code with a few log statements:
console.log("Before query");
postsRef.orderByChild('timeStamp').on('child_added', function(data) {
console.log("In child_added");
});
console.log("After query");
If you run this snippet, the logging will be:
Before query
After query
In child_added
This is probably not the order you expected, since it's different from the order the log statements are in your code. This is because the data is loaded from Firebase asynchronously and the rest of your code continues while it's loading.
It's slightly easier to see if you turn the callback into a separate function:
function onChildAdded(data) {
console.log("In child_added");
});
console.log("Before query");
postsRef.orderByChild('timeStamp').on('child_added', onChildAdded);
console.log("After query");
Now you can more easily see that the first few lines just declare the onChildAdded function. They don't run it yet. And we're just passing that function in to the query, so that the query can call onChildAdded whenever it gets the data.
This is the most common pitfall of web programming with remote servers. But since most of the modern web is based on such asynchronous APIs, you will have to learn it.
One way I've found that works is to reframe your problem. Your current code is based on "first fetch the posts, then add them to the HTML". But in asynchronous programming it's better to think "start fetching the posts. When we get them, add them to the HTML". This translates into the following code:
function fetchPostsleft(postsRef, sectionElement) {
postsRef.orderByChild('timeStamp').on('child_added', function(data) {
var author = data.val().senderName;
topUserPostsSectionleft.getElementsByClassName('posts-containerleft')[0].insertBefore(createheaders(author, ""),
});
};
fetchPostsleft(topUserPostsRef, topUserPostsSectionleft);
Now all the code that needs the new data is inside the callback, so it's only run when the snapshot is actually available.

Calling function in Ionic controller after data loaded

I am pulling data from firebase and depending on the data, I adjust show a different image. My data is taking time to return and the conditional I wrote doesn't do anything because it runs before the data returns. How do I call the function after my data loads? I tried everything on the ionicView Docs. I also tried window.onload but that doesn't work. Thanks for your help in advance.
var firebaseRef = new Firebase("https://app.firebaseio.com/files/0/" + $stateParams.theId);
firebaseRef.once('value', function(dataSnapshot){
var dumData = dataSnapshot.val().data;
//this is just an integer
if (dumData > 3){
document.getElementById("pic").style.backgroundImage = 'url(img/pic2.png';
}
//Please ignore syntax errors as they do not exist in original code
Your issue is not related with ionic.
once returns a promise. So you should use the success callback to handle your data.
From Firebase once documentation:
// Provide a failureCallback to be notified when this
// callback is revoked due to security violations.
firebaseRef.once('value',
function (dataSnapshot) {
// code to handle new value
}, function (err) {
// code to handle read error
});

Return value of crud functions

I have simple table scripts in Azure written in javascript and node.js.
Now, if I call any of these from Windows Phone, the object parameter gets updated automatically from the return value. And thus code like this works
await table1.InsertAsync(val1);
MyObj val2 = new MyObj();
val2.data = val1.Id;
await table2.InsertAsync(val2);
However now I try to utilize this same from scheduled job in Azure: essentially chaining 2 insert calls so that latter depends on the id of the former. The id column is identity and gets created automatically.
How can I achieve this? Scheduled job is written in javascript/node.js. I have tried
var res = table1.insert(val1);
And using val1.id after the first insert, but neither works.
And of course just moments after I post the question I come up with an answer.
table1.insert(val1, {
success: function(res) {
var val2 = {
data: res.id
}
table2.insert(val2);
}
});

Read Sharepoint List Value using javascript and set to variable

I feel I have a fairly simple problem but every solution online is seriously complicated. I am in SharePoint designer 2010 and I am not a programmer but I can get by. I have a SP list with Contract Numbers and when you click the contract number it brings you to the item. I just want JavaScript code that will read the value from the list (by ID or however) and store it in a variable.
For example:
var siteUrl = 'https://...';
var itemID = 22;
var TargetListItem;
Function onLoad(){
var context = new SP.ClientContent(siteUrl);
var web = context.get_web().get_lists().getByTitle('Data Call');
var list = web.getItemById(itemID);
context.load(list, 'Contract Number');
var value = list.get_item('Contract Number');
var url = "/sites/... " + value + "...";
return url
}
The code works if I hard-code value so that the URL returned has a parameter, but not when I set value above. Please if anyone has a really simple way to accomplish this let me know!
You are missing SP.ClientContext.executeQueryAsync method that executes the current pending request asynchronously on the server
SP.ClientContext.executeQueryAsync method has the following signature:
SP.ClientContext.executeQueryAsync(succeededCallback, failedCallback)
and since it is async method you cant return from your method, but have to declare succeededCallback function that contains the returned results.
When working with asynchronous API such as JSOM the following patterns are commonly used:
Using nested callbacks
Using the promises pattern
Please refer Asynchronous programming in apps for Office article to get acquainted with asynchronous programming for SharePoint.
The below example demonstrates how to get list item using callback approach:
function getItem(listTitle,itemId,success,error){
var context = SP.ClientContext.get_current();
var web = context.get_web();
var list = web.get_lists().getByTitle(listTitle);
var listItem = list.getItemById(itemId);
context.load(listItem);
context.executeQueryAsync(
function() {
success(listItem);
},
error
);
}
Example
getItem('Data Call', 22,
function(item){
var result = item.get_item('Contract Number');
},
function(sender,args){
console.log(args.get_message());
}
);
References
How to: Create, Update, and Delete List Items Using JavaScript
Asynchronous programming in apps for Office

Creating relations in parse.com with multiple classes (JavaScript SDK)

Using parse.com and JavaScript SDK.
I've read alot about this, but cannot find any examples that fit my issue I'm trying to solve.
Here is what I'm attempting to achieve.
I want class "FriendRequest" to have a one to many relation with "myBadges". The child objects held in "myBadges" will be increasing overtime.
The child objects are generated by a function that runs when the user selects a badge and uses "Yes, do it now!" to store it in "myBadges".
At the moment I can only seem to create a relationship within the active class that the function uses. This means I have a relation set up in "myBadges" that just points to the User class, not to the class "FriendRequest".
The relation is in this part of code
success: function(results) {
// The object was saved successfully.
userbadges.relation('BadgeConnect').add(userbadges);
userbadges.save();
So the problem I'm trying to solve is to move the relation link from the "myBadges" class to the "FriendRequest" class???
An example answer how how to achieve this would be great to help me learn the correct approach.
FULL CODE.
<script type="text/javascript">
Parse.initialize("xxxx", "xxxxx");
var MyBadges = Parse.Object.extend("myBadges");
var friendRequest = Parse.Object.extend("FriendRequest");
var userbadges = new MyBadges();
var friendRequest = new friendRequest();
var user = Parse.User.current();
$(document).ready(function() {
$("#send").click(function() {
var badgeselected = $('#badgeselect .go').attr("src");
userbadges.set("BadgeName", badgeselected);
userbadges.set("uploadedBy", user);
//userbadges.set('BadgeName');
//userbadges.save();
userbadges.save(null, {
success: function(results) {
// The object was saved successfully.
userbadges.relation('BadgeConnect').add(userbadges);
userbadges.save();
//location.reload();
},
error: function(contact, error) {
// The save failed.
// error is a Parse.Error with an error code and description.
alert("Error: " + error.code + " " + error.message);
}
});
});
});
Like most problems there are many ways to solve it.
If your goal is to be able to query this relationship from either side then I see two main options:
Create a Cloud Function for after-save of your myBadges class that creates a duplicate of the relation on the FriendRequest side. I'm not sure how much support there is for this as I've never tried it.
Create your own relationship class, e.g. myBadges_FriendRequest, inside it have a pointer to each of the other classes, plus anything else you might want to know about that relationship
Personally I recommend the 2nd option. For querying you can easily request information based on either side of the relationship and use include() to populate both pointers in the result as needed.

Categories

Resources