Can placeholders be used only for Database Events in Firebase and not queries? - javascript

Take a look at the following JSON structure:
"Fund_Project_Request" : {
"-LEEy7uxXEeI4AJuePoB" : {
"4ZpTt0rHvjYfKAnCukIlhGpH6kz2" : {
"afds1234" : 2,
"asdf12" : 2
},
"iRfNzDSjFiOADqn3KsG8nNuZEfp2" : {
"afds1234" : 1
}
}
},
Here, if I want to get the values 'afds1234' or 'asdf12' which I'm going to call as 'reward_ids' in an onWrite function, all I have to do is:
exports.manipulateRewards = functions.database.ref('/Fund_Project_Request/{ArtcallID}/{UserID}/{rewardID}').onWrite((change, context) => {
const reward_id = context.params.rewardID;
});
Let's say I want to obtain these reward_ids strings without using the onWrite function. Would I be able to do so with a singleValueEventListener or any other method of querying?

When writing code to query Realtime Database, there are no wildcards. You must know the exact path of the data you're interested in.
Cloud Functions triggers aren't really anything like normal listeners. They are essentially filtering all writes that flow through the system, and triggering only on the writes that match the given path.

Related

Is it possible to get only the updated value with angularfire?

I'm using angularfire and the realtime database
I have a database as so :
actions:{
uid1: {
meta...
},
uid2: {
meta...
},
uid3: {
meta...
},
uid4: {
meta...
},
}
I've made an editor showing all of that actions. Now let say I add an action (uid5) my valueChanges method send me back all the uids when I only need the updated value.
I would do something a bit like this
ngOnInit(){
this.db.object(`actions`).valueChanges().subscribe(
(actions) => console.log(actions) // here I get first time uid1{}, uid2{} ..., uid4{}
//second time after adding uid5 I would get uid5{} only.
)
}
So is it possible, is there some specific event or whatsoever or should I make a feature request?
There is nothing built into Firebase or AngularFire to get only the new items, so you'll have to built something yourself.
The two most common options:
Store a timestamp value in each node, and then query for only items after "now" with something like ref.orderBy("timestamp").startAt(Date.now()).
Start at keys after now, with something like ref.orderByKey().startAt(ref.push().key).

passing non-url encoded parameters to an ajax call in node.js

I am trying to pass parameters from my website to a couchdb server through a node.js server.
I absolutely need to pass {} in a url. Not a string, not an empty object, the actual {} characters. It is used to define the end_key parameter in couchdb views.
At the moment, my call goes like this :
let url = "/trades";
let ajax_options = {
data:{
design_name:'bla',
view_name:'blabla',
params_view:{
group_level:2,
start_key:["1",0],
end_key:["1",{}]
}
}
};
$.ajax(url,ajax_options).then((res) => { ... });
when it passes through NodeJs and the nano library with
db.view(req.query.design_name, req.query.view_name, req.query.params_view)
the end_key object in params_view becomes ["1"] instead of ["1",{}] which I would like to see.
I have verified that with the correct value for end_key, the view gives me the expected result.
How to prevent that behavior from occurring ?

Need Help to implement Tincan Javascript API

I'm working on tincan JavaScript API. The issue my data format is total change and TinCan have specified a why to pass data along with call. Help me to adjust my data in TinCan Api format. Here is sample data one of my call.
var data = {
"groupId": "groupId",
"groupName": "gNameEncrypt",
"tutorNames": "tutorNames",
"actorNames": "actorNames",
"otherNames": "otherNames"
};
Current what i do i simply decode this data and send it like this.
var actionList = new TinCan(
{
recordStores: [{
endpoint: "http://example.com",
username: username,
password: password,
allowFail: false
}]
});
var action = new TinCan.Agent({
"name": "insert"
});
actionList.getStatements({
'params': {
'agent': action,
'verb': {
'id': $.base64.encode(data)
}
},
'callback': function (err, data) {
console.info(data.more);
var urlref = "http://<?php echo $_SERVER['SERVER_NAME'] . ":" . $_SERVER['SERVER_PORT'] . $uriParts[0] . "?" ?>t=" + data.more.TutorToken;
window.location.href = urlref;
}
});
crypt.finish();
});
There are really two parts here:
need to get data into an xAPI (formerly Tin Can) format, and
the code itself.
In depth,
I think you need to take another look at how xAPI is used in general. Data is stored a JSON "Statement" object that has 3 required properties and various other optional ones. These properties often contain complex objects that are very extensible. It is hard to tell from what you've shown what you are really trying to capture and what the best approach would be. I suggest reading some material about the xAPI statement format. http://experienceapi.com/statements-101/ is a good starting point, and to get at least some coverage of all the possibilities continue with http://experienceapi.com/statements/ .
The code you've listed is attempting to get already stored statements based on two parameters rather than trying to store a statement. The two parameters being "agent" and "verb". In this case We can't tell what the verb is supposed to be since we don't know what data contains, I suspect this isn't going to make sense as a verb which is intended to be the action of a statement. Having said that the fact that the "actor" has a value of action is questionable, as that really sounds more like what a "verb" should contain. Getting the statements right as part of #1 should make obvious how you would retrieve those statements. As far as storing those statements, if you're using the TinCan interface object you would need to use the sendStatement method of that object. But this interface is no longer recommended, the recommended practice is to construct a TinCan.LRS object and interact directly with it, in which case you'd be using the saveStatement method.
I would recommend looking at the "Basic Usage" section of the project home page here: http://rusticisoftware.github.io/TinCanJS/ for more specifics look at the API doc: http://rusticisoftware.github.io/TinCanJS/doc/api/latest/

How to retrieve both caller-name and carrier from Twilio in node.js?

Im having problems working with the twilio-api for node.
i wrote this code:
let typeArray = ['caller-name','carrier'];
this.client.phoneNumbers(phoneNumberToCheck).get({
type: typeArray
}, (error, number) => {
// working on the number data results
// ...
});
The problem is that i dont get ANY of them(carrier/caller-name) - although passing array to argument 'type' is the way to do it in other languages(php,c#..) but it doesnt work on node.js, instead i get this:
// -> get
{
"caller_name":null,
"country_code":"US",
"phone_number":"+123456789",
"national_format":"(248) 123-456",
"carrier":null,
"add_ons":null,
"url":"https://lookups.twilio.com/v1/PhoneNumbers/+123456789",
"callerName":null,
"countryCode":"US",
"phoneNumber":"+123456789",
"nationalFormat":"(248) 123-456",
"addOns":null
}
note: if i send each one separately (only carrier or only caller-name) - i get the partial information for each.
how can i get both in one request in node.js?
Twilio developer evangelist here.
You should be calling the Lookups API in Node this way:
client.lookups.phoneNumbers.get(phoneNumber)
.fetch({
type: ['carrier', 'caller-name']
},
function(err, result) {
// do something
}
)
The docs are a little lacking in Node.js on the Lookups documentation and I will raise that with the team.

webOS/Ares : read JSON from URL, assign to label

I've used the webOS Ares tool to create a relatively simple App. It displays an image and underneath the image are two labels. One is static, and the other label should be updated with new information by tapping the image.
When I tap the image, I wish to obtain a JSON object via a URL (http://jonathanstark.com/card/api/latest). The typcial JSON that is returned looks like this:
{"balance":{"amount":"0","amount_formatted":"$0.00","balance_id":"28087","created_at":"2011-08-09T12:17:02-0700","message":"My balance is $0.00 as of Aug 9th at 3:17pm EDT (America\/New_York)"}}
I want to parse the JSON's "amount_formatted" field and assign the result to the dynamic label (called cardBalance in main-chrome.js). I know that the JSON should return a single object, per the API.
If that goes well, I will create an additional label and convert/assign the "created_at" field to an additional label, but I want to walk before I run.
I'm having some trouble using AJAX to get the JSON, parse the JSON, and assign a string to one of the labels.
After I get this working, I plan to see if I can load this result on the application's load instead of first requiring the user to tap.
So far, this is my code in the main-assistant.js file. jCard is the image.
Code:
function MainAssistant(argFromPusher) {}
MainAssistant.prototype = {
setup: function() {
Ares.setupSceneAssistant(this);
},
cleanup: function() {
Ares.cleanupSceneAssistant(this);
},
giveCoffeeTap: function(inSender, event) {
window.location = "http://jonathanstark.com/card/#give-a-coffee";
},
jcardImageTap: function(inSender, event) {
//get "amount_formatted" in JSON from http://jonathanstark.com/card/api/latest
//and assign it to the "updatedBalance" label.
// I need to use Ajax.Request here.
Mojo.Log.info("Requesting latest card balance from Jonathan's Card");
var balanceRequest = new Ajax.Request("http://jonathanstark.com/card/api/latest", {
method: 'get',
evalJSON: 'false',
onSuccess: this.balanceRequestSuccess.bind(this),
onFailure: this.balanceRequestFailure.bind(this)
});
//After I can get the balance working, also get "created_at", parse it, and reformat it in the local time prefs.
},
//Test
balanceRequestSuccess: function(balanceResponse) {
//Chrome says that the page is returning X-JSON.
balanceJSON = balanceResponse.headerJSON;
var balanceAmtFromWeb = balanceJSON.getElementsByTagName("amount_formatted");
Mojo.Log.info(balanceAmtFromWeb[0]);
//The label I wish to update is named "updatedBalance" in main-chrome.js
updatedBalance.label = balanceAmtFromWeb[0];
},
balanceRequestFailure: function(balanceResponse) {
Mojo.Log.info("Failed to get the card balance: " + balanceResponse.getAllHeaders());
Mojo.Log.info(balanceResponse.responseText);
Mojo.Controller.errorDialog("Failed to load the latest card balance.");
},
//End test
btnGiveCoffeeTap: function(inSender, event) {
window.location = "http://jonathanstark.com/card/#give-a-coffee";
}
};
Here is a screenshot of the application running in the Chrome browser:
In the browser, I get some additional errors that weren't present in the Ares log viewer:
XMLHttpRequest cannot load http://jonathanstark.com/card/api/latest. Origin https://ares.palm.com is not allowed by Access-Control-Allow-Origin.
and
Refused to get unsafe header "X-JSON"
Any assistance is appreciated.
Ajax is the right tool for the job. Since webOS comes packaged with the Prototype library, try using it's Ajax.Request function to do the job. To see some examples of it, you can check out the source code to a webOS app I wrote, Plogger, that accesses Blogger on webOS using Ajax calls. In particular, the source for my post-list-assistant is probably the cleanest to look at to get the idea.
Ajax is pretty much the way you want to get data, even if it sometimes feels like overkill, since it's one of the few ways you can get asynchronous behavior in JavaScript. Otherwise you'd end up with code that hangs the interface while waiting on a response from a server (JavaScript is single threaded).

Categories

Resources