I'm trying to read the value from firebase realtime database, but there is no output.
var text = login;
var encoded = btoa(text);
const db = firebase.database();
const func1 = db.ref('users/' + encoded + '/money');
func1.on('value', (snapshot) => {
var data = snapshot.val();
console.log(data);
document.getElementById('some-h1').innerHTML="<h1 class=\"summary\" id=\"some-h1\">" + data + "</h1>";
}, (errorObject) => {
console.log('The read failed: ' + errorObject.name);
});
As I said, there is no output, when the code is executed.
I'll be really thankful, if someone will reply with the solution.
I was trying to set the value of key from my database to be set as text, and I was expecting to show but there is nothing.
Related
I have a node.js Function App which I'm trying to use to retrieve a specific message from a storage queue in order to delete it. It doesnt seem like there is a method to get a specific message by ID, so I'm trying to read all the messages, or at least 32 of them, then find the message to delete by ID.
My problem is I cant seem to figure out how to format the request to specify the number of messages to receive. I am trying to add the option "numberOfMessages" based on this documentation: https://learn.microsoft.com/en-us/javascript/api/#azure/storage-queue/queuereceivemessageoptions?view=azure-node-latest##azure-storage-queue-queuereceivemessageoptions-customheaders
Here is what I have right now that isn't working:
const response = await queueClient.receiveMessages({"numberOfMessages": 32});
context.log("response: " + JSON.stringify(response.receivedMessageItems));
context.log("received messages length: " + response.receivedMessageItems.length);
response is:
[Information] response: [{"messageId":"XXXXXX","insertedOn":"2022-08-28T06:12:45.000Z","expiresOn":"2022-09-04T06:12:45.000Z","popReceipt":"XXXXXXXXX","nextVisibleOn":"2022-08-30T14:57:37.000Z","dequeueCount":858,"messageText":"XXXXXXX"}]
[Information] received messages length: 1
How should I be formatting the option(s)???
edit:
Here is the complete code of index.js in my function app (with redactions):
module.exports = async function (context, req) {
context.log('JavaScript HTTP trigger function processed a request.');
const message = req.body;
const ackType = message.ackType;
if (ackType == 1){
const { QueueServiceClient, StorageSharedKeyCredential } = require("#azure/storage-queue");
const account = "MY_ACCOUNT_NAME";
const accountKey = "MY_ACCOUNT_KEY";
const sharedKeyCredential = new StorageSharedKeyCredential(account, accountKey);
const queueServiceClient = new QueueServiceClient(
`https://${account}.queue.core.windows.net`,
sharedKeyCredential,
{
retryOptions: { maxTries: 4 } // Retry options
}
);
const queueName = "MY_QUEUE_NAME";
const queueClient = queueServiceClient.getQueueClient(queueName);
const response = await queueClient.receiveMessages({"numofmessages": 32});
context.log("response: " + JSON.stringify(response));
context.log("receivedMessageItems: " + JSON.stringify(response.receivedMessageItems));
context.log("received messages length: " + response.receivedMessageItems.length);
}
context.res = {
status: 200 /* Defaults to 200 */
};
}
Here is the queue I am connecting to:
I'm currently tring to exploit a RSS feed to get latest articles from a website.
What I'm doing is to store these data in a MySQL DB. I do that with Javascript, to take informations from the RSS feed.
When I host the script on my server, it's not working anymore.
For the context of programming, on local, I used XAMPP, with a localhost. Then, I do a parcel build, the script being attached to a HTML page, so that I can call it just by loading the WebPage.
I got the error from the title :
Here is the code :
let Parser = require('rss-parser');
let parser = new Parser();
(async () => {
// Connecting to database
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'dataarticles'
});
connection.connect((err) => {
if (err) throw err;
console.log('Connected!');
});
let feed = await parser.parseURL('http://feedrinse.com/services/rinse/?rinsedurl=235e4f5244e1eeb21ce05fc3d4d68cc0');
//== Some console.log to check
// console.log(feed.items[0]['content:encoded']);
//== Some console.log to check
// console.log(feed.items[0].title + "\n"
// + feed.items[0].link + "\n"
// + feed.items[0].contentSnippet + "\n"
// + feed.items[0].pubDate);
// As the feed doesn't provide the minia of article, I take the first image in the content of the test, by searching it
let firstPos = feed.items[0]['content:encoded'].search("https://droidsoft.fr/wp-content/uploads/");
let SecondPos = feed.items[0]['content:encoded'].search('alt="');
let image = feed.items[0]['content:encoded'].substring(firstPos, SecondPos - 2);
let pubDate = feed.items[0].pubDate.substring(5, 16);
//== Some console.log to check
// console.log(image);
// console.log(pubDate);
// We take first item (items[0]) as it's the latest feed. This script is triggered only when there is a new element, so there shouldn't be
// any problem of duplication
connection.query('INSERT INTO `dataarticles` (`Titre`, `URL`, `Description`, `Image`, `date`) VALUES ("' + feed.items[0].title + '", "' + feed.items[0].link + '", "' + feed.items[0].contentSnippet + '", "' + image + '", "' + pubDate + '")', (err, rows) => {
// if (err) throw err;
console.log(rows);
});
})();
I am currently working on a weather station that gets data from OpenWeatherMap's API every 10 minutes.
Every 10 seconds the temperature is published via MQTT in the topic 'local/temperature', so that other systems (for example a heater or air conditioner) can do further actions depending on the temperature.
Every 10 minutes, parallel to the new data retrieval, the weather operations are also published, also via MQTT.
Publishing the data every 10 seconds is a requirement of the project, but not important for this case.
The problem I'm stuck on is this: My request to the API of OWM is done in an extra file, which contains a function that should return the data as an object. At the same time the data is stored in a file, so that in case of a network failure the last local status is saved and can still be used.
I already write into the file, the 'reading when offline' functionality will be added later on. I have also noticed that the assembleURL() function is actually unnecessary, but I haven't changed that yet.
I'm still relatively new in JavaScript / Nodejs, but I already have experience in Java and Python, so it may be that I have mixed in something from Java by mistake.
Can someone please explain to me why the object I return in openWeatherMapCall.js is undefined? I'm thankful for every hint.
My file weather-station.js that calls the function getData in openWeatherMapCall.js:
const mqtt = require('mqtt');
const owm = require('./lib/openWeatherMapCall');
const client = mqtt.connect('mqtt://localhost:1885');
const fs = require('fs');
const config = require('../config/config.json');
const owmConfig = config.owm;
let weatherData = owm.getData(owmConfig.city, owmConfig.owmapikey, owmConfig.lang, "metric");
console.log(weatherData); // -> it says undefined
setInterval(_ => {
weatherData = owm.getData(owmConfig.city, owmConfig.owmapikey, owmConfig.lang, "metric");
client.publish("local/condition", toString(weatherData.weatherID));
console.log('successful publish of wID ' + weatherData.weatherID);
}, 600000); //10 min
setInterval(_ => {
client.publish("local/temperature", toString(weatherData.celsius));
console.log('successful publish of ' + weatherData.celsius + ' celsius');
}, 30000); //10 sec
My OWM API call as openWeatherMapCall.js:
const fetch = require('node-fetch');
const fs = require('fs');
const util = require("util");
function assembleURL (city, apiKey, lang, units){
let url = "http://api.openweathermap.org/data/2.5/weather?q=" + city + "&units=" + units + "&lang=" + lang + "&appid=" + apiKey;
console.log("url: " + url);
return url;
}
function getData(city, apiKey, lang, units){
let url = assembleURL(city, apiKey, lang, units )
fetch(url)
.then(function(resp) { return resp.json() }) // Convert data to json
.then(function(data) {
var currentWeather = {
weather: data.weather[0].description,
weatherID: data.weather[0].id,
celsius: Math.round(parseFloat(data.main.temp)),
wind: data.wind.speed,
location: data.name
};
let toString = JSON.stringify(currentWeather);
fs.writeFile('../config/weather.json', toString, err => {
if (err) {
console.log('Error while writing', err)
} else {
console.log('Successful write')
}
})
return currentWeather;
})
.catch( err => {
console.log('caught it!',err);
});
}
module.exports = {getData};
Return fetch response from getData and use then on owm.getData as fetch returns a Promise.
function getData(city, apiKey, lang, units){
let url = assembleURL(city, apiKey, lang, units )
return fetch(url)....
}
And
owm.getData(owmConfig.city, owmConfig.owmapikey, owmConfig.lang, "metric").then((weatherData) => {
console.log(weatherData)
});
I am working on an Android Application and am using firebase as the back end for it. I am trying to get a notification system working that relies on listening to changes in the database. Having problems though as I am getting the following error. Wondered if anyone would be able to help, any extra code can be supplied.
Firebase Function
'use-strict'
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotification = functions.database.ref("Notifications/{user_id}/{notification_id}").onWrite((data, context)=>{
const user_id = context.params.user_id;
const notification_id = context.params.notification_id;
console.log("User ID : " + user_id + " | Notification ID : " + notification_id);
return admin.database().ref("Notifications/" + user_id + "/" + notification_id).get().then(queryResult => {
const job_id = queryResult.data().Job;
const from_data = admin.database().ref("Jobs/" + job_id).get();
const to_data = admin.database().ref("Users/" + user_id).get();
return Promise.all([from_data, to_data]).then(result => {
const job_name = result[0].data().advertName;
const to_name = result[1].data().fullName;
console.log("JOB : " + job_name + " | TO : " + to_name);
return undefined;
});
});
});
Function Error
It looks like you're mixing up the Realtime Database and Firestore APIs. Firebase Realtime Database APIs doens't provide a get() method to fetch data. For that, you use once() on a Reference object.
The error is pretty explicit: there is no get function in the a Firebase Realtime Database.
You seem to be trying to use Cloud Firestore, which is available under admin.firestore(). So something like:
const from_data = admin.firestore().doc("Jobs/" + job_id).get();
const to_data = admin.firestore().doc("Users/" + user_id).get();
For full samples see the NODE.JS tab in the Getting started and other Firestore documentation.
I have a global variable (openTokSessionID) that is set by a function. When the function is run again, it should check to see if openTokSessionID is set. If it is, it should use the current value. Instead, however, it complains that openTokSessionID is undefined. My server code is below. Thanks for your help.
var http = require('http').createServer(handler),
io = require('socket.io').listen(http).set('log level', 1),
opentok = require('opentok'),
key = '', // Replace with your API key
secret = ''; // Replace with your API secret
var ot = new opentok.OpenTokSDK(key,secret);
ot.setEnvironment("staging.tokbox.com");
//ot.setEnvironment("api.opentok.com"); //only for production
http.listen(8080);
console.log('Chatserver listening on port 8080');
var nicknames = {};
var log = {};
var connectedUsersObject={};
var privateSessionObject={};
var data;
var openTokSessionID='';
function handler(req, res) {
res.writeHead(200);
res.end();
}
////////////////////////////////////////////SOCKET.IO FUNCTIONS///////////////////////////////////////////////////////
io.sockets.on('connection', function (socket) {
socket.on('private message', function(data) {
console.log('OpenTok Session ID is: ....' + openTokSessionID);
if(data.messageType=='openTokDemoRequest'){ //if new session, create unique session ID, add to current chat object
console.log(data.messageType + ' sender: ' + data.from);
var location = '127.0.0.1'; // use an IP or 'localhost'
console.log('message type is: "openTokDemoRequest". openTokSessionID is: ' + openTokSessionID);
var messageRecipient=data.from;
if(openTokSessionID==''){
console.log('The session ID is: ' + openTokSessionID + '++++++++');openTokSessionID= ot.create_session(location, function(openTokSessionID){
var data= {'to':messageRecipient, 'message':{'token': ot.generate_token({'session_id':openTokSessionID, 'role': "publisher"}), 'sessionID': openTokSessionID, 'apikey':key}, 'from': 'openTok', 'messageType':'demoTokenInfo', 'privateSessionID':''};
console.log('NEW session id is: ' + openTokSessionID + '. token is: ' + data.message.token);
// privateMessageSend(data);
// sendToUser(data);
connectedUsersObject[messageRecipient].emit('private message', data);
console.log ('message recipient is: ' + messageRecipient);
});
}
else{
console.log('OpenTok Session ID is: ////' + openTokSessionID);
var data= {'to':messageRecipient, 'message':{'token': ot.generate_token({'session_id':openTokSessionID, 'role': "publisher"}), 'sessionID': openTokSessionID, 'apikey':key}, 'from': 'openTok', 'messageType':'demoTokenInfo', 'privateSessionID':''};
console.log('session id is: ' + openTokSessionID + '. token is: ' + data.message.token);
connectedUsersObject[messageRecipient].emit('private message', data);
console.log ('message recipient is: ' + messageRecipient);
}
}
});
Here you're trying to use the return value from an asynchronous call, and as a result you're setting your variable to undefined:
openTokSessionID= ot.create_session(location, function(openTokSessionID){
...
Because you gave your callback argument the same name as your variable, it masked your variable within the callback so it looked OK the first time, but your actual variable got trashed.
You need to change it to something like:
ot.create_session(location, function(sessionID){
openTokSessionID = sessionID;
...