Return value of crud functions - javascript

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);
}
});

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.

Calculated fields in json API?

I'm wondering to which extend should we add in an API values that can be calculated from the raw data and extra available information (from the browser session, user interface.. or whatever)
For example, we could have an API returning this JSON:
{
ownder_id: '123',
canAddComment: true,
etc...
}
That gives us the value "canAddComment" directly.
Or we could have just this:
{
ownder_id: '123',
etc...
}
Where, comments can be calculated from the owner_id. For example, a user can add comments if the session owner_id is different from the received from the API.
We could have done this in Javascript instead:
//supposing we have a session object with our browser session values
var params = {owner_id: session.owner_id};
$.post(apiURL, params, function(data){
var result = JSON.parse(data);
//processing the data
result["canAddComments"] = result.owner_id !== session.owner_id;
//do whatever with it
});
What would be the best approach? What's the recommendation in this kind of cases?
I'm not exactly sure what you want to know. But my first reaction is you make a function out of it.
// constructor
function Comment() {
this.owner_id;
this.canAddComment = function() {
return session.user_id === this.owner_id;
}
}
var session = {
user_id: 22,
name: 'Kevin'
};
var my_comment = new Comment();
my_comment.owner_id = 15;
if(my_comment.canAddComment()) {
$.ajax({
// now read the form and submit the data ...
})
}
else {
alert('Only the author of this message can update ...');
}
EDIT:
My question was mainly if this should better be calculated in the backend side or calculated after retrieving the API data.
Not sure if there is a generic answer. A few arguments: if you want the method to be secret, you must do it on server side. In other cases, I think it makes perfect sense to let the client PC use its processing power.
Okay, one example: sorting. Let's say there is a table full of data; clicking on the head sorts the table according to that column. Does it make sense to send all the data to the server, let it sort the table and return an array of keys? No, I think it makes more sense to let the client process this.
http://tablesorter.com/docs/
Similar with Google Maps: you drag a marker to some place, then the program must calculate the closest 5 bus stops. Well, obviously you calculate all of this on client side.

How can I cleanly pull a Parse.Object relation's records when fetching the object?

In the Parse JavaScript guide, on the subject of Relational Data it is stated that
By default, when fetching an object, related Parse.Objects are not
fetched. These objects' values cannot be retrieved until they have
been fetched.
They also go on to state that when a relation field exists on a Parse.Object, one must use the relation's query().find() method. The example provided in the docs:
var user = Parse.User.current();
var relation = user.relation("likes");
relation.query().find({
success: function(list) {
// list contains the posts that the current user likes.
}
});
I understand how this is a good thing, in terms of SDK design, because it prevents one from potentially grabbing hundreds of related records unnecessarily. Only get the data you need at the moment.
But, in my case, I know that there will never be a time when I'll have more than say ten related records that would be fetched. And I want those records to be fetched every time, because they will be rendered in a view.
Is there a cleaner way to encapsulate this functionality by extending Parse.Object?
Have you tried using include("likes")?
I'm not as familiar with he JavaScript API as the ObjC API.. so in the example below I'm not sure if "objectId" is the actual key name you need to use...
var user = Parse.User.current();
var query = new Parse.Query(Parse.User);
query.equalTo(objectId, user.objectId);
query.include("likes")
query.find({
success: function(user) {
// Do stuff
}
});
In general, you want to think about reverse your relationship. I'm not sure it is a good idea be adding custom value to the User object. Think about creating a Like type and have it point to the user instead.
Example from Parse docs:
https://parse.com/docs/js_guide#queries-relational
var query = new Parse.Query(Comment);
// Retrieve the most recent ones
query.descending("createdAt");
// Only retrieve the last ten
query.limit(10);
// Include the post data with each comment
query.include("post");
query.find({
success: function(comments) {
// Comments now contains the last ten comments, and the "post" field
// has been populated. For example:
for (var i = 0; i < comments.length; i++) {
// This does not require a network access.
var post = comments[i].get("post");
}
}
});
Parse.Object's {Parse.Promise} fetch(options) when combined with Parse.Promise's always(callback) are the key.
We may override fetch method when extending Parse.Object to always retrieve the relation's objects.
For example, let's consider the following example, where we want to retrieve a post and its comments (let's assume this is happening inside a view that wants to render the post and its comments):
var Post = Parse.Object.extend("Post"),
postsQuery = new Parse.Query(Post),
myPost;
postsQuery.get("xWMyZ4YEGZ", {
success: function(post) {
myPost = post;
}
).then(function(post) {
post.relation("comments").query().find({
success: function(comments) {
myPost.comments = comments;
}
});
});
If we had to do this every time we wanted to get a post and its comments, it would get very repetitive and very tiresome. And, we wouldn't be DRY, copying and pasting like 15 lines of code every time.
So, instead, let's encapsulate that by extending Parse.Object and overriding its fetch function, like so:
/*
models/post.js
*/
window.myApp = window.myApp || {};
window.myApp.Post = Parse.Object.extend("Post", {
fetch: function(options) {
var _arguments = arguments;
this.commentsQuery = this.relation("comments").query();
return this.commentsQuery.find({
success: (function(_this) {
return function(comments) {
return _this.comments = comments;
};
})(this)
}).always((function(_this) {
return function() {
return _this.constructor.__super__.fetch.apply(_this, _arguments);
};
})(this));
}
});
Disclaimer: you have to really understand how closures and IIFEs work, in order to fully grok how the above works, but here's what will happen when fetch is called on an existing Post, at a descriptive level:
Attempt to retrieve the post's comments and set it to the post's comments attribute
Regardless of the outcome of the above (whether it fails or not) operation, always perform the post's default fetch operation, and invoke all of that operation's callbacks

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

Extracting the number of facebook likes and setting a javascript variable to this number

I need the number of facebook likes, which I get through
https://graph.facebook.com/?ids=http://www.stackoverflow.com
it is a json output:
{
"http://www.stackoverflow.com": {
"id": "http://www.stackoverflow.com",
"shares": 4984,
"comments": 2
}
}
But how to extract this number 4984 and to set a javascript variable to this number?
Please, show a small working example.
thanks
Graph API have support of JSONP, so you may use callback argument to call your function which will set the desired variable:
var likes;
function setLikes(data){
likes = data.shares;
console.log('Got results', data.id, likes);
}
var s = document.createElement('script');
s.src = 'https://graph.facebook.com/?id=http://www.stackoverflow.com&callback=setLikes';
document.getElementsByTagName('head')[0].appendChild(s);
Note: I've changed ids to id which is simplify output if you only need details for one OpenGraph object. If you need to get info for many objects you'll need to change a bit setLikes method to loop over keys or get info by desired key data['http://www.stackoverflow.com'].shares
Update:
Due to asynchronous nature of previous call you'll need to wait with code that depend on likes until getLikes called. This may be done in many ways, look to the next code to get some clue...
var likes; // This is a variable scoped outside of setLikes!
function setLikes(data){
// Once this is set likes will be available everywhere in the scope it defined!
likes = data.shares;
// You may run code that depends on likes variable here
call_function_that_depends_on_likes();
// You can also fire an event that your code subscribed to
// and pass likes as an argument...
// If you using Facebook JS-SDK
FB.Event.fire('my-custom-event', likes);
// If you using jQuery
$(document).trigger('my-custom-event', likes)
}
// If you using Facebook JS-SDK
FB.Event.subscribe('my-custom-event', function(likes){
// Run your code from here
});
// If you using jQuery
$(document).on('my-custom-event', function(evt, likes){
// Run your code from here
});
You've probably already done something similar if you used domready or document.load.
If you have that object in a variable output, you would read it like this:
var likes = output["http://www.stackoverflow.com"].shares;
But I gather that you also wonder how to retrieve that value from Facebook? Here is using the popular javascript library jQuery:
$.getJSON("https://graph.facebook.com/?ids=http://www.stackoverflow.com&callback=?", function(response) {
var likes = response["http://www.stackoverflow.com"].shares;
// Go do something with likes here
});

Categories

Resources