How to turn do make these function in to chaining function? - javascript

Am trying to use the chaining method but am not sure how to that yet. I have researched online and still haven't found any success any help will be appreciated.
// The URL root if user searches by city
const API_ROOT_CITY = "http://api.geonames.org/searchJSON?q=";
// Parameters for geonames
const API_ROOT_PARAMS = "&maxRows=1"
// API KEY for geonames
const API_KEY = &username=kamara.moses;
// WeatherBit URL
const API_ROOT_BIT = "https://api.weatherbit.io/v2.0/forecast/daily?"
// Parameters for weatherbit
const API_BIT_PARAMS = "&city="
// API KEY for weatherbit
const API_BIT_KEY = "&key=cda6df51d9a24b8c9d54b830f4eadb51"
// PixaBay URL
const API_ROOT_PIXA = "https://pixabay.com/api/?"
// API KEY for pixabay
const API_PIXA_KEY = "key=19853981-85155ca595da994be43f034e6"
// Parameters for pixabay
const API_PIXA_PARAMS = "&q="
// Type of image from pixabay
const API_PIXA_IMAGE = "&image_type=photo"
// Main function of the program
// Grabs the user"s input, then forms URL, calls API, POSTS and updates UI
function clickRespond() {
// Grab user"s input
const cityInput = document.getElementById("city");
// Read values of zip and city
const city = cityInput.value;
// Form URL based on zip or city search
// (zip takes precendence if both were entered)
let url;
let bitURL;
let pixaURL;
if (city) {
url = API_ROOT_CITY + city + API_ROOT_PARAMS + API_KEY;
bitURL = API_ROOT_BIT + API_BIT_PARAMS + city + API_BIT_KEY;
pixaURL = API_ROOT_PIXA + API_PIXA_KEY + API_PIXA_PARAMS + API_PIXA_IMAGE;
}
// Call the API
getGeo(url)
// Prepares data for POST, calls the POST
.then(function (response) { // CHANGE: call it response
console.log(response)
const errorMessage = document.getElementById("error");
if (response.status == "200") { // CHANGE: check the status
errorMessage.classList.add("hide");
const city = response.geoNames.geonames[0].name; // Change
postJournal("/add", { city }) ;
// Calls to update the site with latest entry
updateUI();
} else {
console.log("Bad data entered");
errorMessage.classList.remove("hide");
return;
}
})
getWeather(bitURL)
.then(function (response) {
console.log(response)
const errorMessage = document.getElementById("error");
if (response.status == "200") {
errorMessage.classList.add("hide");
const icon = response.weatherBit.data[0].weather.icon;
const description = response.weatherBit.data[0].weather.description
const newDate = dateTime();
const date = newDate;
const highTemp = response.weatherBit.data[0].high_temp;
const lowTemp = response.weatherBit.data[0].low_temp
postJournal("/add", { icon: icon, description: description, date: date, highTemp: highTemp, lowTemp: lowTemp });
// Calls to update the site with latest entry
updateUI();
} else {
console.log("Bad data entered");
errorMessage.classList.remove("hide");
return;
}
})
getPix(pixaURL)
.then(function (response) {
console.log(response)
const errorMessage = document.getElementById("error");
if (response.status == "200") {
errorMessage.classList.add("hide");
const image = response.pixaBay.hits[0].webformatURL;
postJournal("/add", { image: image });
// Calls to update the site with latest entry
updateUI();
} else {
console.log("Bad data entered");
errorMessage.classList.remove("hide");
return;
}
})
}

Related

Is there a javascript function to identify which endpoint is hit through fetch

i want to check specific endpoints which are running on specific events.
I have a function which is working fine with xhr type of request but i want to get the response with fetch type of requests and not finding a way to do that.
(function () {
var proxied = window.XMLHttpRequest.prototype.open;
window.XMLHttpRequest.prototype.open = function (requestType, endPoint) {
var pointer = this;
var intervalId = window.setInterval(() => {
if (pointer.readyState != 4) return;
const end_point_list = [
'/cart/add.js',
'/cart/update.js',
'/cart/change.js',
'/cart/clear.js',
'/cart/add',
'/cart/update',
'/cart/change',
'/cart/clear',
];
const method = pointer._method;
const url = pointer._url;
console.log(url)
if (end_point_list.includes(url) && method.toUpperCase() === 'POST') {
console.log(url)
const responseBody = pointer.response
? JSON.parse(pointer.response)
: '';
const shop_name = window.Shopify.shop;
console.log({ url, responseBody, shop_name });
}
clearInterval(intervalId);
}, 1);
proxied.apply(this, arguments);
};
})();

Firebase Database console.log() returning Null in Javascript

I hope to seek help from someone if possible. In the following code. Im trying to console.log() data from My Firebase reference as you can see in my code below. But the Console.log() is returning null instead of the values that are there in Firebase Realtime Database. I have also provided the code for adding which is working well. Please have a look the image of my database if it helps. I am not getting any other error in my console except the fact that this is returning null.
function addFamilyMember() {
var NameOfMember = document.getElementById("newFamilyMemberName").value;
var DoBOfMember = document.getElementById("newFamilyMemberDoB").value;
var EmailOfMember = document.getElementById("newFamilyMemberEmail").value;
var ContactOfMember = document.getElementById("newFamilyMemberContactNo").value;
if (
NameOfMember.length == "" ||
DoBOfMember.length == "" ||
EmailOfMember.length == "" ||
ContactOfMember.length == ""
) {
alert("Please enter all details of your Family Member");
} else {
var user = firebase.auth().currentUser;
var uid;
if (user != null) {
uid = user.uid;
}
firebase
.database()
.ref("/Users/" + uid + "/Family/" + NameOfMember)
.set({
MemberName: NameOfMember,
MemberDOB: DoBOfMember,
MemberEmail: EmailOfMember,
MemberContact: ContactOfMember,
});
}
}
var user = firebase.auth().currentUser;
var uid;
if (user != null) {
uid = user.uid;
}
firebase
.database()
.ref("/Users/" + uid + "/Family/")
.on("value", function (snap) {
var mName = snap.child("MemberName").val();
var mDOB = snap.child("MemberDOB").val();
var mEmail = snap.child("MemberEmail").val();
var mContact = snap.child("MemberContact").val();
console.log(mName + " " + mEmail + " " + mContact + " " + mDOB);
});
The problem is you are fetching the whole Family node and trying to access data of each member.
I tried to recreate your database structure and got this in console on running the code.
{
"Name One": {"MemberContact":10000,"MemberName":"Name Two"},
"Name Two": {"MemberContact":10002,"MemberName":"Name Two"}
}
so if you want to get data of each user from that then try using forEach this way.
Object.keys(snap.val()).forEach(key => {
const memberData = snap.val()[key]
//Data of each member
var mName = memberData["MemberName"]
var mDOB = memberData["MemberDOB"]
var mEmail = memberData["MemberEmail"]
var mContact = memberData["MemberContact"]
console.log(mName + " " + mEmail + " " + mContact + " " + mDOB);
})
When loading the page for the first time, firebase.auth().currentUser shouldn't be used because Firebase Auth needs to check if the user's login session is valid first.
let currentUserFamilyRef = null;
// for use with .on("value") and .off("value")
function onValueFamilyListener(snapshot) {
const familyMembers = [];
snapshot.forEach((familyMemberSnapshot) => {
const MemberName = snap.child("MemberName").val();
const MemberDOB = snap.child("MemberDOB").val();
const MemberEmail = snap.child("MemberEmail").val();
const MemberContact = snap.child("MemberContact").val();
familyMembers.push({ MemberName, MemberDOB, MemberEmail, MemberContact });
console.log(MemberName + " " + MemberDOB + " " + MemberEmail + " " + MemberContact);
}
// TODO: do something with the array of family members familyMembers
}
// for showing loading state
function showLoadingIcon(visible) {
if (visible) {
// TODO: show the icon
// TODO: disable the submit button
} else {
// TODO: hide the icon
// TODO: enable the submit button
}
}
// for when addFamilyMember() is called while signed out
function addFamilyMemberSignedOut() {
alert('You need to sign in first!');
return false;
}
// for when addFamilyMember() is called while signed in
function addFamilyMemberSignedIn() {
const NameOfMember = document.getElementById("newFamilyMemberName").value;
const DoBOfMember = document.getElementById("newFamilyMemberDoB").value;
const EmailOfMember = document.getElementById("newFamilyMemberEmail").value;
const ContactOfMember = document.getElementById("newFamilyMemberContactNo").value;
if (
NameOfMember.length == "" ||
DoBOfMember.length == "" ||
EmailOfMember.length == "" ||
ContactOfMember.length == ""
) {
alert("Please enter all details of your Family Member");
return false;
}
const user = firebase.auth().currentUser;
if (user === null) {
// shouldn't get here, but just in case.
alert('You need to sign in first!');
return false;
}
const uid = user.uid;
showLoadingIcon(true);
firebase
.database()
.ref("/Users/" + uid + "/Family/" + encodeURIComponent(NameOfMember)) // escape names as they may contain symbols, etc.
.set({
MemberName: NameOfMember,
MemberDOB: DoBOfMember,
MemberEmail: EmailOfMember,
MemberContact: ContactOfMember,
})
.then(
() => {
// saved family member's data successfully
showLoadingIcon(false);
// reset form
document.getElementById("newFamilyMemberName").value = "";
document.getElementById("newFamilyMemberDoB").value = "";
document.getElementById("newFamilyMemberEmail").value = "";
document.getElementById("newFamilyMemberContactNo").value = "";
alert('Information saved!');
},
(err) => {
// failed to save family member's data
showLoadingIcon(false);
// err.code may lead to more specific error information
console.error(err);
alert('Failed to save information!');
}
);
}
// for calling the correct addFamilyMember version
let addFamilyMember = addFamilyMemberSignedOut;
showLoadingIcon(true); // while loading the user's info, show a loading icon
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// A user is (newly/already) signed in.
// create a reference for this user's family
const newUserFamilyRef = firebase.database()
.ref("/Users/" + user.uid + "/Family");
if (currentUserFamilyRef !== null) {
// if the old user and new user are the same, do nothing
// but if they've changed, remove the old listener and update currentUserFamilyRef
if (!currentUserFamilyRef.isEqual(newUserFamilyRef)) {
currentUserFamilyRef.off("value", onValueFamilyListener);
currentUserFamilyRef = newUserFamilyRef;
}
} else {
currentUserFamilyRef = newUserFamilyRef;
}
// use the "signed in" version of addFamilyMember
addFamilyMember = addFamilyMemberSignedIn;
// attach listener to "/users/{user.uid}/Family"
currentUserFamilyRef.on("value", onValueFamilyListener);
} else {
// no user is signed in.
// use the "not signed in" version of addFamilyMember
addFamilyMember = addFamilyMemberSignedOut;
// if a user was logged in, clean up it's listener to prevent errors
if (currentUserFamilyRef !== null) {
currentUserFamilyRef.off("value", onValueFamilyListener);
}
// no user, so set the reference to null
currentUserFamilyRef = null;
}
showLoadingIcon(false);
});
You can't directly use firebase.auth().currentUser. First you need to check the authentication state of the user. Then only you can ask for the current user. So to do this you need to wrap it using authentication state observer.You can read more about it on firebase documentation: [https://firebase.google.com/docs/auth/web/start][1]
function addFamilyMember() {
var NameOfMember = document.getElementById("newFamilyMemberName").value;
var DoBOfMember = document.getElementById("newFamilyMemberDoB").value;
var EmailOfMember = document.getElementById("newFamilyMemberEmail").value;
var ContactOfMember = document.getElementById("newFamilyMemberContactNo").value;
firebase.auth().onAuthStateChanged((user) => {
if (user) {
if (
NameOfMember.length == "" ||
DoBOfMember.length == "" ||
EmailOfMember.length == "" ||
ContactOfMember.length == ""
) {
alert("Please enter all details of your Family Member");
} else {
var user = firebase.auth().currentUser;
var uid;
if (user != null) {
uid = user.uid;
}
firebase
.database()
.ref("/Users/" + uid + "/Family/" + NameOfMember)
.set({
MemberName: NameOfMember,
MemberDOB: DoBOfMember,
MemberEmail: EmailOfMember,
MemberContact: ContactOfMember,
});
}
}
var user = firebase.auth().currentUser;
var uid;
if (user != null) {
uid = user.uid;
}
firebase
.database()
.ref("/Users/" + uid + "/Family/")
.on("value", function (snap) {
var mName = snap.child("MemberName").val();
var mDOB = snap.child("MemberDOB").val();
var mEmail = snap.child("MemberEmail").val();
var mContact = snap.child("MemberContact").val();
console.log(mName + " " + mEmail + " " + mContact + " " + mDOB);
})
})}

ReferenceError: value is not defined CloudFunction

ïm trying to send a notifications to all the users that a device have in firebase database, but it says: "ReferenceError: value is not defined" in the register of the cloud function.
What is supposed to do is: every time a change is made in "Notifications", you must obtain the data that was changed, with this data look in the device table and send a notification to all the tokens that are in that device.
This is the error:
Code of the cloudfunction:
const functions = require('firebase-functions');
const admin = require('firebase-admin'); // this is the Admin SDK, not firebase-functions
admin.initializeApp(functions.config().firebase);
const db = admin.database()
const ms = admin.messaging()
exports.notifications = functions.database.ref('Notifications/{id}').onUpdate(async(evt) =>{
const payload = {
notification:{
title : 'Alarma se activó tu cerca',
body : 'Se activó tu cerca, revisala',
badge : '1',
sound :'defaul'
}
};
//Get Notification Device ID
const notySnap = await db.ref('Notification/').once('value');
var devicee = notySnap.notty;
var dev = JSON.stringify(devicee);
//Get number of users that the device had
const usersSnap = await db.ref('Devices/'+ dev + '/Users').once(value)
const nUsers = usersSnap.nUsers;
var Nusers = JSON.stringify(nUsers);
var nNUsers = parseInt(Nusers);
//Send notification to the number of users that exist
if (Nusers !== null){
for(i = 1; 1 <=nNUsers; i++){
if(i === 1){
const userToSendP1 = usersSnap.user1;
var userToSend1 = JSON.stringify(userToSendP1);
Console.log("Mensaje enviado a user 1");
return ms.sendToDevice(userToSend1, payload);
}else if(i === 2){
const userToSendP2 = usersSnap.user2;
var userToSend2 = JSON.stringify(userToSendP2);
Console.log("Mensaje enviado a user 2");
return ms.sendToDevice(userToSend2, payload);
}else if(i === 2){
const userToSendP3 = usersSnap.user3;
var userToSend3 = JSON.stringify(userToSendP3);
Console.log("Mensaje enviado a user 3");
return ms.sendToDevice(userToSend3, payload);
}else if(i === 2){
const userToSendP4 = usersSnap.user4;
var userToSend4 = JSON.stringify(userToSendP4);
Console.log("Mensaje enviado a user 4");
return ms.sendToDevice(userToSend4, payload);
}
}
}
return null
})
DataBase:
In this line:
const usersSnap = await db.ref('Devices/'+ dev + '/Users').once(value)
value is a variable that you never defined. That's what the error message means. You probably meant this instead, with 'value' as a string:
const usersSnap = await db.ref('Devices/'+ dev + '/Users').once('value')

Nodejs Scraper isn't moving to next page(s)

Hey guys this is a follow on from my other question, i have created a Nodejs Scraper that doesnt seem to want to go through the pages, it stays on the first. my source code is below
const rp = require('request-promise');
const request = require('request');
const otcsv = require('objects-to-csv');
const cheerio = require('cheerio');
//URL To scrape
const baseURL = 'xxx';
const searchURL = 'xxxx';
//scrape info
const getCompanies = async () => {
// Pagination test
for (let index = 1; index <= 20; index = index + 1) {
const html = await rp.get(baseURL + searchURL + index);
const $ = await cheerio.load(html);
console.log("Loading Pages....");
console.log("At page number " + index);
// end pagination test
//const htmls = await rp(baseURL + searchURL);
const businessMap = cheerio('a.business-name', html).map(async (i, e) => {
const link = baseURL + e.attribs.href;
const innerHtml = await rp(link);
const emailAddress = cheerio('a.email-business', innerHtml).prop('href');
const name = e.children[0].data || cheerio('h1', innerHtml).text();
const phone = cheerio('p.phone', innerHtml).text();
return {
// link,
name,
emailAddress: emailAddress ? emailAddress.replace('mailto:', '') : '',
phone,
}
}).get();
return Promise.all(businessMap);
}
};
console.log("Finished Scraping.... Now Saving!")
//save to CSV
getCompanies()
.then(result => {
const transformed = new otcsv(result);
return transformed.toDisk('./output.csv');
})
.then(() => console.log('Scrape Complete :D '));
As you can see I have tried a few different ways to make this happen so any help will be gratefully appreciated.

How to get specific data from API and use in function?

I'm trying to build a weather app in nodejs with dark-sky API. I got a separate js file and keep my forecast info in a callback function. However, I also want to use Skycons for visualization.
this is my forecast.js. in that script I get info like temperature etc. so I need to get "icon" data as well
const request = require('request')
const getWeather = (latitude, longitude, callback) => {
const url = 'https://api.darksky.net/forecast/b0854aec02e1655c7203e05c7d77dfd1/' + latitude + ',' + longitude + '/?units=si'
request({
url: url,
json: true
}, (error, {
body /* "response " evezine response object icindeki "body" birbasa daxil edirem function-a*/
}) => {
if (error) {
callback('Unable to connect to weather service!', undefined)
} else if (body.error) {
callback('Unable to find location'.undefined)
} else {
callback(undefined,
'It is currently ' + body.currently.temperature + '°C out in ' + body.timezone + '. Weather ' + body.daily.data[0].summary + ' There is a ' + (body.currently.precipProbability * 100) + '% chance of rain.'
)
}
})
}
module.exports = getWeather
This is the fetch function, and I tried to invoke and activate Skycons in this function. but I cannot get "icon" data from API.
const weatherForm = document.querySelector("form");
const search = document.querySelector("input");
const messageOne = document.querySelector("#message-1");
const messageTwo = document.querySelector("#message-2");
const skycons = new Skycons({
color: '#222'
})
skycons.set('icon', 'clear-day');
skycons.play();
const icon = data.forecast.icon;
weatherForm.addEventListener("submit", e => {
e.preventDefault();
const location = search.value;
messageOne.textContent = "Please wait....";
messageTwo.textContent = "";
fetch(
"http://localhost:4000/weather?address=" + encodeURIComponent(location)
).then(response => {
response.json().then(data => {
if (data.error) {
messageOne.textContent = data.error;
} else {
messageOne.textContent = data.location;
messageTwo.textContent = data.forecast;
}
currentSkycons(icon, document.getElementById('icon'));
});
});
messageOne.textContent;
messageTwo.textContent;
});
function currentSkycons(icon, iconID) {
const currentIcon = icon.replace(/-/g, "_").toUppercase();
skycons.play();
return skycons.set(iconID, Skycons[currentIcon]);
}
but to use Skycons, I need to get "icon" from the dark-sky API. how I can get this data aside from my forecast js? To get and assign that data to a variable and use in another function
It looks like the data object is only accessible in the response json, which means you would need to access forcast.icon when you have the response.

Categories

Resources