Using $priority with $push in AngularFire - javascript

I tried to push data to firebase using the following code and it works fine.
var firebaseObj = new Firebase("https://burning-fire-1723.firebaseio.com/Articles");
var fb = $firebase(firebaseObj);
fb.$push({
title: "title",
post: "post",
emailId: "mymail#gmail.com"
}).then(function(ref) {
console.log(ref);
}, function(error) {
console.log("Error:", error);
});
Next, in order to fetch a particular record from Firebase I need to assign a priority to emailId field while pushing the data.
But I really can't figure out how to do that.
Any help would be appreciated.

This should do it for you.
var user = "mymail#gmail.com";
var firebaseObj = new Firebase("https://burning-fire-1723.firebaseio.com/Articles");
var fb = $firebase(firebaseObj);
fb.$push({
title: title,
post: post,
emailId: user,
'.priority': user
}).then(function(ref) {
console.log(ref);
$location.path('/welcome');
}, function(error) {
console.log("Error:", error);
});
The answer came from this this tutorial.

Related

Parse Cloud Code - Add To Array

Tried loads of different variations with my cloud code and I can't get it to work. Basically I've got a push notification function, and in this function I want to add an object to a PFUser's array, but you can't use a master key in Xcode so here's what I have:
Parse.Cloud.define("iOSPush", function (request, response) {
console.log("Inside iOSPush");
var data = request.params.data;
var not_class = request.params.not_class;
var not_objectid = request.params.not_objectid;
var not_date = request.params.not_date;
var userid = request.params.userid;
var recipientUser = new Parse.Query(Parse.User);
recipientUser.equalTo("objectId", userid);
// set installation query:
var pushQuery = new Parse.Query(Parse.Installation);
pushQuery.equalTo('deviceType', 'ios');
pushQuery.matchesQuery('user', recipientUser);
pushQuery.find({ useMasterKey: true }).then(function(object) {
response.success(object);
console.log("pushQuery got " + object.length);
}, function(error) {
response.error(error);
console.error("pushQuery find failed. error = " + error.message);
});
// send push notification query:
Parse.Push.send({
where: pushQuery,
data: data
}, { useMasterKey: true }).then(function() {
console.log("### push sent!");
// create notification:
var notification = {
"title": not_class,
"body": request.params.data.alert,
"class": not_class,
"objectId": not_objectid,
"date": not_date
};
// get notifications:
var tmp_notifications = recipientUser.get("notifications");
// add notification:
tmp_notifications.push(notification);
// update with notifications:
recipientUser.set("notifications", tmp_notifications);
recipientUser.save();
}, function(error) {
console.error("### push error" + error.message);
});
response.success('success. end of iospush');
});
The Xcode cloud function I have provides the correct information, the function gets to the end.. just the function is not setting the notifications for some reason
I ended up figuring out the answer to this post myself. The reason this didn't work is because I needed to first fetch the user object in a separate query, then save it using the master key. I also found out that there's a function for appending data onto an existing array without having to create another one (parseObject.add()):
var userQ = new Parse.Query(Parse.User);
userQ.get(userid, {
success: function(theuser) {
console.log("### got userrrrrrrrrr!");
theuser.add("notifications", n_object);
theuser.save(null, {useMasterKey:true});
},
error: function(object, error) {
// The object was not retrieved successfully.
// error is a Parse.Error with an error code and message.
}
});
This set of code was executed just before:
response.success('success. end of iospush');

How to use servicebus topic sessions in azure functionapp using javascript

I have an Azure Functionapp that processes some data and pushes that data into an Azure servicebus topic.
I require sessions to be enabled on my servicebus topic subscription. I cannot seem to find a way to set the session id when using the javascript functionapp API.
Here is a modified extract from my function app:
module.exports = function (context, streamInput) {
context.bindings.outputSbMsg = [];
context.bindings.logMessage = [];
function push(response) {
let message = {
body: CrowdSourceDatum.encode(response).finish()
, customProperties: {
protoType: manifest.Type
, version: manifest.Version
, id: functionId
, rootType: manifest.RootType
}
, brokerProperties: {
SessionId: "1"
}
context.bindings.outputSbMsg.push(message);
}
.......... some magic happens here.
push(crowdSourceDatum);
context.done();
}
But the sessionId does not seem to get set at all. Any idea on how its possible to enable this?
I tested sessionid on my function, I can set the session id property of a message and view it in Service Bus explorer. Here is my sample code.
var connectionString = 'servicebus_connectionstring';
var serviceBusService = azure.createServiceBusService(connectionString);
var message = {
body: '',
customProperties:
{
messagenumber: 0
},
brokerProperties:
{
SessionId: "1"
}
};
message.body= 'This is Message #101';
serviceBusService.sendTopicMessage('testtopic', message, function(error)
{
if (error)
{
console.log(error);
}
});
Here is the test result.
Please make sure you have enabled the portioning and sessions when you created the topic and the subscription.

NodeJS - Updating object on request

I have the following object:
var user = {
firstName: req.body.first_name,
lastName: req.body.last_name,
email: req.body.email,
password: "",
id: "",
};
Now what I'm trying to do is post a request to the API and if the user is successfully saved in the database, it will return a user id as well as a password (Which can then be emailed to the person)..
request.post({
url: process.env.API_SIGNEDIN_ENDPOINT + "users/store",
form: user,
headers: {
Authorization: "Bearer " + req.session.authorization
}
}, function(error, response, body) {
// Check the response
var theResponse = JSON.parse(response.body);
if(theResponse.code == 400)
{
var error = [
{param: "email", msg: "This email address has already been taken!", value: ""}
];
res.render("create", {
errors: error,
});
}else{
var theUser = JSON.parse(body);
user.password = theUser.password;
user.id = theUser.id;
}
});
This is working fine, however, whenever I try to output user it's not updating the user object outside of this post. The user object is fine and it's working, the issue seems to be from when I try and access the user from this result callback. Any ideas?
EDIT:
Let's say I have "address1" (This is the persons main address) and I have "address2" (This is the persons second address).. The person might only have 1 address and therefore I only need to save one address. However using the logic that place everything in the .then() means I cannot do this because the user might not have 2 addresses but I still need to access the main address, for example:
mainAddress.save().then(function(addressData) {
var theAddressLicenceTick = req.body.address_licence;
if(theAddressLicenceTick)
{
var subAddress = models.addresses.build({
address_1: "asasfasf",
city: "asfafsaf",
postcode: "asfasf",
created_at: new Date(),
updated_at: new Date();
});
subAddress.save().then(function(subAddress) {
// continue integration
// would I have to do the functionality again?
});
}else{
// The user only has one address
}
});
Essentially, I have a customer table which can have multiple addresses through a link table. But I believe that there is an easier way instead of writing all of this code?

How to get data from Firebase database to ionic?

I am having an issue (new to JavaScript and ionic) regarding Firebase database. I have a code to display the name of a user :
.controller('accountController',['$scope', '$firebaseArray', 'CONFIG', '$document', '$state', function($scope, $firebaseArray, CONFIG, $document, $state) {
var userId = '-KcsNqRpO70spcMIPaKg';
return firebase.database().ref('/accounts/' + userId).once('value').then(function(snapshot) {
var displayName = snapshot.val().name;
$scope.$apply(function() {
$scope.displayName = displayName;
});
console.log(displayName);
// ...
});
}])
This works fine when I use directly the -KcsNqRpO70spcMIPaKg, but I would like my code to get directly this string by simply matching the logged in user to its account in the database.
I tried using var userId = firebase.auth().currentUser.uid; instead, but it doesn't grab the -KcsN..., instead it grabs the actual uid from the authentication.
I am lost. I do not understand how to grab it. Any ideas?
Alright, after searching for hours, I hope I will help a newbie just like me for this matter, the answer is to actually use "Set" instead of push and to rename your random key created by Firebase to the UID of the user :
firebase.database().ref().child('/accounts/' + user.uid).set({
name: userSignup.displayname,
email: userSignup.cusername,
password: userSignup.cpassword,
description: "No description for this user",
facebook: "",
twitter: "",
}).then(function() {
// Update successful.
$state.go("login");
}, function(error) {
// An error happened.
console.log(error);
});

angularjs message binding doesn't show until second form submit [duplicate]

This question already has an answer here:
How come Angular doesn't update with scope here?
(1 answer)
Closed 8 years ago.
I'm writing my first angularjs app, and it's beginning to make sense. However, I have a sign up form that isn't getting the messages in some cases to alert users to problems. I'm using Firebase to authenticate, which works fine. But I'm storing users by a unique username as the key. So before I run the $createUser function, I do a quick query to see if there's already a user object with this key-- if not, I create the user.
The problem is when there is an existing user with this username. The console log value prints fine, but the error message (bound to $scope.authMsg) doesn't show up the first time-- but if I click the "register" button again, then the message shows up in the expected message div.
Any hints on the message issue (or suggestions for this code) would be appreciated!
$scope.register = function() {
$scope.authMsg = '';
var ref = new Firebase(FIREBASE_URL);
$scope.authObj = $firebaseAuth(ref);
// check if the username is taken
ref.child("/users/"+$scope.account.username).on("value", function(snapshot) {
if (snapshot.val()) {
//
// PROBLEM HERE!!
//
$scope.authMsg = 'Username exists-- did you forget your password?'; // doesn't show on page until second submit
console.log('Username exists-- did you forget your password?'); // prints to console as expected
} else {
$scope.authObj.$createUser({ email: $scope.account.email, password: $scope.account.password })
.then(function(userData) {
console.dir(userData);
return $scope.authObj.$authWithPassword({
email: $scope.account.email,
password: $scope.account.password
});
}).then(function(authData) {
// we created a user and are now logged in-- store user info
var userdata = {};
userdata[$scope.account.username] = {
uid: authData.uid,
first_name: $scope.account.first_name,
last_name: $scope.account.last_name,
email: $scope.account.email,
full_name: $scope.account.first_name+' '+$scope.account.last_name
};
var usersRef = ref.child("users");
// save the userdata
usersRef.set(userdata);
console.log("Logged in as:", authData.uid);
$state.go('app.dashboard');
}).catch(function(error) {
$scope.authMsg = error;
console.error("Error: ", error);
});
}
}, function (errorObject) {
$scope.authMsg = 'The read failed: ' + errorObject.code;
console.log('The read failed: ' + errorObject.code);
});
};
I'm assuming, the Firebase callback does not involve an angular digest cycle.
To handle this, write
if (snapshot.val()) {
$scope.$apply(function() {
$scope.authMsg = 'Username exists— did you forget your password?';
});
A useful reading about the topic: http://jimhoskins.com/2012/12/17/angularjs-and-apply.html

Categories

Resources