I am trying to find out all the records that matches a user from a Parse class (namely, UserBeaconTracking). I am able to get correct user object and beacon object to begin with. However, when I use the statement
userBeaconTrackingQuery.equalTo("user", user);
Returned Error 102 with an error message "value is expected instead of map type."
What is it that I am doing wrong?
Here is the code snippet:
var userQuery = new Parse.Query(Parse.User);
userQuery.equalTo("username", username);
userQuery.find().then(function(currentUser) { // get the user who sent the request
user = currentUser;
console.log("User" + JSON.stringify(user) + "Beacon Name :: " + JSON.stringify(visitedBeaconName));
}).then(function () { // get the beacons with which user communicated
var beaconRelation = Parse.Object.extend("Beacon");
var beaconQuery = new Parse.Query(beaconRelation);
beaconQuery.equalTo("name", visitedBeaconName);
return beaconQuery.find();
}).then(function (beacons) { // get user beacon transaction details
console.log("number of beacons " + beacons.length + " " + beacons[0]);
visitedBeacon = beacons[0];
console.log("beacon :: " + visitedBeacon);
var userBeaconTracking = Parse.Object.extend("UserBeaconTracking");
var userBeaconTrackingQuery = new Parse.Query(userBeaconTracking);
userBeaconTrackingQuery.equalTo("user", user);
userBeaconTrackingQuery.equalTo("beacon", visitedBeacon);
userBeaconTrackingQuery.find({
success : function (results) {
visitCounter = results[0].get("count");
console.log ("Visit Counter :: " + visitCounter);
// get the list of stores associated with the beacon
var beaconTable = Parse.Object.extend("Beacon");
var brandsAssociatedWithBeacon = new Parse.Query(beaconTable);
brandsAssociatedWithBeacon.get(visitedBeacon.id).then(function(beacon) {
typeOfBeacon = beacon.get("type");
console.log("Beacon Type ::" + typeOfBeacon);
var beaconBrandRelation = beacon.relation("brand");
var query = beaconBrandRelation.query();
//return query.find();
});
},
error: function(error) {
console.log("Error: " + error.code + " " + error.message);
}
});
});
Related
I am still trying to build my website where people can text each other, send photos etc.
The chat thing works really well until I wanna add the functionality checking whether the second user in the chat is typing.
Here is my code without the typing thing, this works really well ;)
firebase.initializeApp(firebaseConfig);
const db = firebase.database();
// temporary user and receiver's names
const username = prompt("Nickname:");
const receiver = prompt("Receiver's name:");
// sending a message
document.getElementById("send-message").addEventListener("submit", postChat);
function postChat(e)
{
e.preventDefault();
const timestamp = Date.now();
const chatTxt = document.getElementById("chat-txt");
const message = chatTxt.value;
chatTxt.value = "";
db.ref("messages/" + username + "/" + receiver + "/" + timestamp).set({
usr: username,
msg: message,
});
db.ref("messages/" + receiver + "/" + username + "/" + timestamp).set({
usr: username,
msg: message,
});
}
// printing the message
const fetchChat = db.ref("messages/" + username + "/" + receiver + "/");
fetchChat.on("child_added", function (snapshot)
{
const messages = snapshot.val();
const msg = "<li>" + messages.usr + " : " + messages.msg + "</li>";
document.getElementById("messages").innerHTML += msg;
});
The problem appears when I want to check if the second user is typing. When I am adding the code that's below messages just stop to work. There is a random null in the database as a new user who sent a message to another null. The chat between users also stops to work, users don't see same messages, sometimes can't see any of them and always "undefined" types "undefined" when I refresh the website.
At least it correctly shows when someone is typing, but the rest of the functionalities (which used to work) just don't work anymore.
Here is the code of the typing thing, I also tried to check whether the username and receiver's name aren't null but it didn't reallly help.
// showing whether the receiver is typing
function sendTyping(tmp)
{
if(tmp)
{
db.ref("messages/" + username + "/" + receiver).set({
tpg: "yes"
});
}
else
{
db.ref("messages/" + username + "/" + receiver).set({
tpg: "no"
});
}
}
var searchTimeout;
document.getElementById("chat-txt").onkeydown = function() {
if (searchTimeout != undefined)
clearTimeout(searchTimeout);
searchTimeout = setTimeout(callServerScript, 1500);
sendTyping(true);
}
function callServerScript() {
sendTyping(false);
}
let areTheyTyping = db.ref("messages/" + receiver + "/" + username);
areTheyTyping.on("value", function(snapshot) {
const typing = snapshot.val();
const status = typing.tpg;
if(status == "yes")
document.getElementById("writing").innerHTML = "typing...";
else
document.getElementById("writing").innerHTML = "";
});
I mostly wrote this by myself, I will appreciate any kind of help, just please use a straightforward language so I can easily understand the explanation of the problem, I am kind of new.
The function
const fetchChat = db.ref("messages/" + username + "/" + receiver + "/");
fetchChat.on("child_added", function (snapshot)
{
const messages = snapshot.val();
const msg = "<li>" + messages.usr + " : " + messages.msg + "</li>";
document.getElementById("messages").innerHTML += msg;
});
It fetches the chat whenever a child is added to the directory of your messages, so when you store the typing status in "messages/" + username + "/" + receiver + "/" the function .on knows that you've changed/added something, therefore posting a message. It's undefined because the message is in fact empty. You should create a new directory where you store the areTheyTyping status, something like "status/" + username + "/" + receiver + "/" Hope I helped.
My experience showed that firestore has problem with undefined values. You can try adding a default value for undefined or null usernames. Maybe you can add zero (0) as the default value for this matter.
Change the path db.ref("messages/" + receiver + "/" + username) to db.ref("messages/" + username + "/" + receiver) at areTheyTyping. See if it works
function sendTyping(tmp)
{
if(tmp) {
db.ref("messages/" + username + "/" + receiver).set({
tpg: "yes"
});
}
else {
db.ref("messages/" + username + "/" + receiver).set({
tpg: "no"
});
}
}
var searchTimeout;
document.getElementById("chat-txt").onkeydown = function() {
if (searchTimeout !== undefined)
clearTimeout(searchTimeout);
searchTimeout = setTimeout(callServerScript, 1500);
sendTyping(true);
}
function callServerScript() {
sendTyping(false);
}
let areTheyTyping = db.ref("messages/" + username + "/" + receiver);
areTheyTyping.on("value", function(snapshot) {
const typing = snapshot.val();
const status = typing.tpg;
if(status === "yes")
document.getElementById("writing").innerHTML = "typing...";
else
document.getElementById("writing").innerHTML = "";
});
Passing variables within the functions : I want to pass mentioned variable (insTypeDB) to another function. Please see the image.
//Getting Symbol details from DB API
var insTypeDB;
pm.sendRequest("http://192.168.14.116:8080/ords/unidata/symbol/symbol/" + dataArr[1], function (err, response) {
var resBoday = response.json()
insTypeDB = resBoday.items[0].instrument_type_id;
//var intInsTypeDB = parseInt(insTypeDB);
console.log("insTypeDB " + insTypeDB);
//pm.expect(insTypeDB).is.to.equals(2);
});
//Verify Instrument Type with DB API
pm.test("Row : " + i + " - " + dataArr[1] + " : Verify symbol Instrument type with DB", function () {
let insTypeRes = dataArr[2];
let intInsType = parseInt(insTypeRes);
console.log("insType " + intInsType);
pm.expect(insTypeDB).is.to.equals(intInsType);
});[enter image description here][1]
Passing Variables error
//Getting Symbol details from DB API
var insTypeDB;
pm.sendRequest("http://192.168.14.116:8080/ords/unidata/symbol/symbol/" + dataArr[1], function (err, response) {
var resBoday = response.json()
insTypeDB = resBoday.items[0].instrument_type_id;
//var intInsTypeDB = parseInt(insTypeDB);
console.log("insTypeDB " + insTypeDB);
//pm.expect(insTypeDB).is.to.equals(2);
//Verify Instrument Type with DB API
pm.test("Row : " + i + " - " + dataArr[1] + " : Verify symbol Instrument type with DB", function () {
let insTypeRes = dataArr[2];
let intInsType = parseInt(insTypeRes);
console.log("insType " + intInsType);
pm.expect(insTypeDB).is.to.equals(intInsType);
});[enter image description here][1]
});
add the test inside the sendRequest as it is a call back else use setTimeOut which will wait for the value to be populated
pm.sendRequest("http://192.168.14.116:8080/ords/unidata/symbol/symbol/" + dataArr[1], function (err, response) {
var resBoday = response.json()
insTypeDB = resBoday.items[0].instrument_type_id;
//var intInsTypeDB = parseInt(insTypeDB);
console.log("insTypeDB " + insTypeDB);
pm.varaible.set("insTypeDB",insTypeDB);
});
setTimeout(()=>{
pm.test("Row : " + i + " - " + dataArr[1] + " : Verify symbol Instrument type with DB", function () {
let insTypeRes = dataArr[2];
let intInsType = parseInt(insTypeRes);
console.log("insType " + intInsType);
pm.expect(pm.varaible.get("insTypeDB")).is.to.equals(intInsType);
})
},5000)
I send a request from the client to the server and the server responses back to both the client and the controller with a token. Then, the client receives the token back and sign the token with some extra information (Client IP, time and own blockchain address). After, the client sends the signed information with its own public key. All is good until here.
Now, the controller receives the message with signed information and the public key. Tries to verify this signed information with the coming public key and the message which already has.
Here is Client part code:
var message = token + "," + client.address().address + "," + time + "," + my_public;
var message_buf = Buffer.from(message);
const sign = crypto.createSign('SHA256');
sign.write(message_buf);
sign.end();
const signature = sign.sign(my_private, 'hex');
var sign_pub = signature.toString() + "," + my_public.toString();
var sign_pub_buf = Buffer.from(sign_pub);
console.log("sign_pub = ", sign_pub_buf);
client.send(sign_pub_buf, sdn_port, host, function(error){
if(error){
client.close();
}
else{
console.log('Sign+Public_K has been sent to SDN !!!');
}
Here is Controller part code:
udpsocket_sdn.on('message', function(msg, rinfo) {
console.log('Data received from CLIENT : ' ,msg);
var sig_pub = msg.toString().split(",");
var sig = sig_pub[0];
var pub = sig_pub[1];
console.log("sig = ", sig);
console.log("pub = ", pub);
var message = token + "," + rinfo.address + "," + time + "," + pub;
var message_buf = Buffer.from(message);
const verify = crypto.createVerify('SHA256');
verify.write(message_buf);
verify.end();
var isGood = verify.verify(pub, sig, 'hex');
if(isGood){
console.log('All Good');
}
else {
console.log('Nope !');
}
}
Ok, I fixed it. It is working now.
Here is the Client part code:
const { privateKey, publicKey } = crypto.generateKeyPairSync('rsa', {
modulusLength: 2048,
});
var my_public = publicKey.export({type: 'spki', format: 'pem'});
var my_private = privateKey;
var time = 100;
client.on('message',function(msg, info){
if(data_cnt == 1){
console.log('Random number received from SERVER !');
data_cnt++;
var token_tot = msg.toString().split(",")
usr1_pub_pem = token_tot[0];
token = token_tot[1];
var message = token + "," + ip + "," + time + "," + Buffer.from(my_public);
console.log("Client address = ", ip)
const sign = crypto.createSign('SHA256');
sign.write(message);
sign.end();
const signature = sign.sign(my_private, 'hex');
client.send(signature, sdn_port, host, function(error){
if(error){
client.close();
}
else{
console.log('Signature has been sent to SDN !!!');
client.send(my_public, sdn_port, host, function(error){
if(error){
client.close();
}
else{
console.log('Public Key has been sent to SDN !!!');
}
});
}
});
}
});
Now, the Controller part :
var time = 100;
udpsocket_sdn.on('message', function(msg, rinfo) {
count_sdn = count_sdn + 1;
if(count_sdn == 1){
console.log('Signature data received from CLIENT !!');
sig_pub = msg.toString();
}
else if (count_sdn == 2){
console.log('Public key data received from CLIENT !! ');
pub = msg;
var message = token + "," + rinfo.address + "," + time + "," + pub;
console.log("Client address = ", rinfo.address)
const verify = crypto.createVerify('SHA256');
verify.write(message);
verify.end();
var isGood = verify.verify(pub, sig_pub, 'hex');
if(isGood){
console.log('All Good');
}
else {
console.log('Nope !');
}
}
});
I have used node.js and request.js to access form information from our email services API. With the console.log in the function I am able to see all the info that I need. I have tried to access it outside of the function with dot notation(request.missionStatement) which I don't think is right. I want to be able to display this on a page within an express.js app.
var request = require('request');
// Basic Authentication credentials
var username = "user";
var password = "password";
var authenticationHeader = "Basic " + new Buffer(username + ":" + password).toString("base64");
// Search for Custom Data Objects Affiliate Falculty form
request(
{
url : "url to api",
headers : { "Authorization" : authenticationHeader }
},
function (error, response, body) {
var parsedData = JSON.parse(body);//convert text from API to JSON file
var missionStatement = [];
for (var i = 0; i < parsedData.elements.length ; i++) {
var individualStatement = "";
//Get text submission from form and push into array
individualStatement += (parsedData.elements[i].fieldValues[4].value + ", " + parsedData.elements[i].fieldValues[2].value + " " + parsedData.elements[i].fieldValues[3].value + ", " + parsedData.elements[i].fieldValues[0].value);
missionStatement.push(individualStatement);
};
console.log(missionStatement)
}
);
The variable missionStatement is a local variable declared inside an anonymous function passed as an argument to the request function, and thus it is inaccessible once the anonymous function returns. You must save your result elsewhere. Try something like this:
var request = require('request');
// Basic Authentication credentials
var username = "user";
var password = "password";
var authenticationHeader = "Basic " + new Buffer(username + ":" + password).toString("base64");
var result;
// Search for Custom Data Objects Affiliate Falculty form
request(
{
url : "url to api",
headers : { "Authorization" : authenticationHeader }
},
function (error, response, body) {
var parsedData = JSON.parse(body);//convert text from API to JSON file
var missionStatement = [];
for (var i = 0; i < parsedData.elements.length ; i++) {
var individualStatement = "";
//Get text submission from form and push into array
individualStatement += (parsedData.elements[i].fieldValues[4].value + ", " + parsedData.elements[i].fieldValues[2].value + " " + parsedData.elements[i].fieldValues[3].value + ", " + parsedData.elements[i].fieldValues[0].value);
missionStatement.push(individualStatement);
};
result = missionStatement;
displayResult();
});
function displayResult() {
console.log(result);
}
Your missionStatement will now be saved in result, but only after the anonymous callback to request() has been called (when the actual request is finished).
I have the following data array in my Firebase app. I want to delete Account3 using AngularFire's $remove method but I can't get it to work
[MY-FIREBASE-URL]
users
simplelogin:1
accounts
0
title: "Account1"
1
title: "Account2"
2
title: "Account3"
3
title: "Account4"
4
title: "Account5"
This is the code I'm using
var fbURL = [MY-FIREBASE-URL];
var ref = new Firebase(fbURL);
var authData = ref.getAuth();
if (authData) {
console.log("User " + authData.uid + " is logged in with " + authData.provider);
var accountPath = fbURL + "/users/" + authData.uid + "/accounts/" + account.title;
//alert(accountPath);
var accountRef = new Firebase(accountPath);
accountRef.remove();
} else {
console.log("User is logged out");
}
In the console.log I see the correct user in the authData but nothing happens. What am I doing wrong?
Try this. I altered the accountRef variable and your $remove() function:
var fbURL = [MY-FIREBASE-URL];
var ref = new Firebase(fbURL);
var authData = ref.getAuth();
if (authData) {
console.log("User " + authData.uid + " is logged in with " + authData.provider);
var accountPath = fbURL + "/users/" + authData.uid + "/accounts/" + account.title;
//alert(accountPath);
var accountRef = $firebaseObject(accountPath);
accountRef.$remove().then(function(accountPath) {
console.log("data has been deleted locally and in Firebase");
}, function(error) {
console.log("Error:", error);
});
} else {
console.log("User is logged out");
}
Thank you #MattDionis for you help. I finally found the answer to my question so here it is for any other newbies like me struggling with a similar issue. In the sample code above the Firebase URL was referencing "account.title" which in fact I needed "account.id", based on the data structure above, to actually remove the entry from my Firebase data.