My script written in NodeJS connects to Firebase, checks my Firebase Database and even successfully sends notifications when results from my database return true... However, it only works when I run it from my local machine. I deploy it to Firebase and it will not work. Could someone please advise? Thank you.
I hate asking on here because I'm a newbie but I have spent hours tonight trying to find an answer...
INDEX.JS
// Firebase Functions
const functions = require('firebase-functions');
var admin = require("firebase-admin");
// Default admin firebase configuration
admin.initializeApp(functions.config().firebase);
// var serviceAccount = require("xxxxxx-80xxxxd-firebase-adminsdk- xxxxxxx.json");
var moment = require('moment');
var FCM = require('fcm-push');
var dateTime = require('node-datetime');
var serverKey = 'xxxxxxxxxxxxxpSELZBjQYwpZgmxxxxxxxxxxx';
var fcm = new FCM(serverKey);
//Initial function call:
exports.CheckDates = functions.https.onRequest((req, response) => {
// Get a database reference to our posts
var db = admin.database();
var ref = db.ref("records");
var userToken = '';
var itemExpires = '';
var itemName = '';
var reminded = '';
var itemCount = 0;
var counter = 1;
var itemFoundCount = 0;
var dt = dateTime.create();
var formatted = dt.format('m-d-Y');
ref.once("value", function (recordsSnapshot) {
recordsSnapshot.forEach(function (recordsSnapshot) {
var mainKey = recordsSnapshot.key;
recordsSnapshot.forEach(function (child) {
var key = child.key;
var value = child.val();
if (key == 'Account') {
userToken = value.userToken;
}
if (key == 'Items') {
recordsSnapshot.child("Items").forEach(function (itemsSnapshot) {
counter++;
if (itemFoundCount === 0) {
itemFoundCount = itemsSnapshot.numChildren();
}
var itemsChildkey = itemsSnapshot.key;
var itemsChildvalue = itemsSnapshot.val();
itemExpires = itemsChildvalue.itemExpires;
itemName = itemsChildvalue.itemName;
reminded = itemsChildvalue.reminded;
moment().format('YYYY-MM-DD');
var currentDate = moment();
var otherTime = moment(reminded);
if (typeof reminded !== 'undefined') {
if (currentDate.diff(otherTime, 'days') >= 30) {
if (currentDate.diff(itemExpires, 'days') <= 90) {
itemCount++;
console.log("Expire date is less than " +
currentDate + " by 90 days = " + (currentDate.diff(otherTime, 'days') <=
90));
db.ref("records/" + mainKey + "/Items/" +
itemsChildkey + '/reminded').set(formatted);
}
}
} else {
itemCount++;
db.ref("records/" + mainKey + "/Items/" + itemsChildkey +
`enter code here`'/reminded').set(formatted);
}
if (counter == itemFoundCount && itemCount > 0) {
console.log(itemFoundCount);
var message = {
to: userToken, // required fill with device token or
topics
notification: {
title: 'Item Expire Notification',
body: itemCount + ' is about to expire.'
}
};
//callback style
fcm.send(message, function (err, response) {
if (err) {
console.log("Something has gone wrong!");
} else {
console.log("Successfully sent with response: ",
response);
}
});
itemCount = 0;
itemFoundCount = 0;
counter = 1;
}
});
}
});
});
});
response.send(200, "ok");
}) // END exports.CheckDates
Obviously, I remove the Exports.CheckDates lines when I run it locally but it wasn't showing up at all without the exports on Firebase's console. It returns warnings locally and on Firebase console but it works on one and not the other.
Please disregard this question. The script adds the date that the last time a notification was sent to the item's "Reminded" key in the database... this prevents notifications from going out every day for the same thing..
It ran on my local machine, and did it's job but I couldn't figure out why it wouldn't run again... well, ha! At least we know that part works.
Related
As you can imagine, stripe and authorize.net and other payment gateway services offer an api that can only be hit via server-side for safety reasons. Currently the documentation for Authorize.net allows for me to create an express node app and then run the command node charge-credit-card.js (which works and gets a 200 response from their api) My question is two parts. How do I connect my server directory (aptly named named AuthorizePaymentNode in the image below this paragraph) with my angular src app directory(aptly named named FoodOrderingApp in the image) to gather the card info on the front end so that I may process a credit card from start to finish? Secondly assuming I get it working in development how and where do I upload my AuthorizePaymentNode directory along with my FoodOrderingApp so that the two work together. Do I do it in two separate places as a friend of mine suggested or can it just be done all at once and in one place?
[https://i.stack.imgur.com/ibUDr.png][1]
charge-credit-card.js (works like a charm when running node charge-credit-card.js)
var ApiContracts = require('authorizenet').APIContracts;
var ApiControllers = require('authorizenet').APIControllers;
var SDKConstants = require('authorizenet').Constants;
var utils = require('./utils.js');
var constants = require('./constants.js');
function chargeCreditCard(callback) {
var merchantAuthenticationType = new ApiContracts.MerchantAuthenticationType();
merchantAuthenticationType.setName(constants.apiLoginKey);
merchantAuthenticationType.setTransactionKey(constants.transactionKey);
var creditCard = new ApiContracts.CreditCardType();
creditCard.setCardNumber('4242424242424242');
creditCard.setExpirationDate('0822');
creditCard.setCardCode('999');
var paymentType = new ApiContracts.PaymentType();
paymentType.setCreditCard(creditCard);
var orderDetails = new ApiContracts.OrderType();
orderDetails.setInvoiceNumber('INV-12345');
orderDetails.setDescription('Product Description');
var tax = new ApiContracts.ExtendedAmountType();
tax.setAmount('4.26');
tax.setName('level2 tax name');
tax.setDescription('level2 tax');
var duty = new ApiContracts.ExtendedAmountType();
duty.setAmount('8.55');
duty.setName('duty name');
duty.setDescription('duty description');
var shipping = new ApiContracts.ExtendedAmountType();
shipping.setAmount('8.55');
shipping.setName('shipping name');
shipping.setDescription('shipping description');
var billTo = new ApiContracts.CustomerAddressType();
billTo.setFirstName('Ellen');
billTo.setLastName('Johnson');
billTo.setCompany('Souveniropolis');
billTo.setAddress('14 Main Street');
billTo.setCity('Pecan Springs');
billTo.setState('TX');
billTo.setZip('44628');
billTo.setCountry('USA');
var shipTo = new ApiContracts.CustomerAddressType();
shipTo.setFirstName('China');
shipTo.setLastName('Bayles');
shipTo.setCompany('Thyme for Tea');
shipTo.setAddress('12 Main Street');
shipTo.setCity('Pecan Springs');
shipTo.setState('TX');
shipTo.setZip('44628');
shipTo.setCountry('USA');
var lineItem_id1 = new ApiContracts.LineItemType();
lineItem_id1.setItemId('1');
lineItem_id1.setName('vase');
lineItem_id1.setDescription('cannes logo');
lineItem_id1.setQuantity('18');
lineItem_id1.setUnitPrice(45.00);
var lineItem_id2 = new ApiContracts.LineItemType();
lineItem_id2.setItemId('2');
lineItem_id2.setName('vase2');
lineItem_id2.setDescription('cannes logo2');
lineItem_id2.setQuantity('28');
lineItem_id2.setUnitPrice('25.00');
var lineItemList = [];
lineItemList.push(lineItem_id1);
lineItemList.push(lineItem_id2);
var lineItems = new ApiContracts.ArrayOfLineItem();
lineItems.setLineItem(lineItemList);
var userField_a = new ApiContracts.UserField();
userField_a.setName('A');
userField_a.setValue('Aval');
var userField_b = new ApiContracts.UserField();
userField_b.setName('B');
userField_b.setValue('Bval');
var userFieldList = [];
userFieldList.push(userField_a);
userFieldList.push(userField_b);
var userFields = new ApiContracts.TransactionRequestType.UserFields();
userFields.setUserField(userFieldList);
var transactionSetting1 = new ApiContracts.SettingType();
transactionSetting1.setSettingName('duplicateWindow');
transactionSetting1.setSettingValue('120');
var transactionSetting2 = new ApiContracts.SettingType();
transactionSetting2.setSettingName('recurringBilling');
transactionSetting2.setSettingValue('false');
var transactionSettingList = [];
transactionSettingList.push(transactionSetting1);
transactionSettingList.push(transactionSetting2);
var transactionSettings = new ApiContracts.ArrayOfSetting();
transactionSettings.setSetting(transactionSettingList);
var transactionRequestType = new ApiContracts.TransactionRequestType();
transactionRequestType.setTransactionType(ApiContracts.TransactionTypeEnum.AUTHCAPTURETRANSACTION);
transactionRequestType.setPayment(paymentType);
transactionRequestType.setAmount(utils.getRandomAmount());
transactionRequestType.setLineItems(lineItems);
transactionRequestType.setUserFields(userFields);
transactionRequestType.setOrder(orderDetails);
transactionRequestType.setTax(tax);
transactionRequestType.setDuty(duty);
transactionRequestType.setShipping(shipping);
transactionRequestType.setBillTo(billTo);
transactionRequestType.setShipTo(shipTo);
transactionRequestType.setTransactionSettings(transactionSettings);
var createRequest = new ApiContracts.CreateTransactionRequest();
createRequest.setMerchantAuthentication(merchantAuthenticationType);
createRequest.setTransactionRequest(transactionRequestType);
//pretty print request
console.log(JSON.stringify(createRequest.getJSON(), null, 2));
var ctrl = new ApiControllers.CreateTransactionController(createRequest.getJSON());
//Defaults to sandbox
//ctrl.setEnvironment(SDKConstants.endpoint.production);
ctrl.execute(function(){
var apiResponse = ctrl.getResponse();
var response = new ApiContracts.CreateTransactionResponse(apiResponse);
//pretty print response
console.log(JSON.stringify(response, null, 2));
if(response != null){
if(response.getMessages().getResultCode() == ApiContracts.MessageTypeEnum.OK){
if(response.getTransactionResponse().getMessages() != null){
console.log('Successfully created transaction with Transaction ID: ' + response.getTransactionResponse().getTransId());
console.log('Response Code: ' + response.getTransactionResponse().getResponseCode());
console.log('Message Code: ' + response.getTransactionResponse().getMessages().getMessage()[0].getCode());
console.log('Description: ' + response.getTransactionResponse().getMessages().getMessage()[0].getDescription());
}
else {
console.log('Failed Transaction.');
if(response.getTransactionResponse().getErrors() != null){
console.log('Error Code: ' + response.getTransactionResponse().getErrors().getError()[0].getErrorCode());
console.log('Error message: ' + response.getTransactionResponse().getErrors().getError()[0].getErrorText());
}
}
}
else {
console.log('Failed Transaction. ');
if(response.getTransactionResponse() != null && response.getTransactionResponse().getErrors() != null){
console.log('Error Code: ' + response.getTransactionResponse().getErrors().getError()[0].getErrorCode());
console.log('Error message: ' + response.getTransactionResponse().getErrors().getError()[0].getErrorText());
}
else {
console.log('Error Code: ' + response.getMessages().getMessage()[0].getCode());
console.log('Error message: ' + response.getMessages().getMessage()[0].getText());
}
}
}
else {
console.log('Null Response.');
}
callback(response);
});
}
if (require.main === module) {
chargeCreditCard(function(){
console.log('chargeCreditCard call complete.');
});
}
module.exports.chargeCreditCard = chargeCreditCard;
cart.ts
let total = item.price * item.quantity;
item.options.forEach(option => (total += option.value * item.quantity));
return total;
}
get totalAmount() {
let total = 0;
this.cart.forEach(item => (total += this.getItemTotal(item)));
return total;
}```
[1]: https://i.stack.imgur.com/ibUDr.png
using the accept suite seems to be the most logical answer
I have a code where I need to upload bulk records like (50,000) from an CSV. From angular 6, we are making an restapi call from where we are passing the formdata to node server. In node portion we are looping that set of records(50,000) and we are uploading it in to our backend by splitting it like 1500. Records will be uploaded for every consecutive 1500.
So In our local it is working completely fine & we have tested uploading same 50000 records. But we have moved the same code to our SIT environment where we are facing the error. After uploading certain amount of record (20000 records), again its starts uploading from first record. This is some weird behaviour, which we couldnt test it in local. Can anyone please please suggest What I need to do?
var bulkUploadData = async function (jsonblob, res) {
var payloadjson = [];
var jsonResponse = {};
try {
for (let i = 0; i < jsonblob.length; i++) {
if(jsonblob[i].PN != null){
var JFB = {}
var arrayy = [];
if (jsonblob[i].Otyp != "L") {
JFB.srv = jsonblob[i].SA;
JFB.ptype = jsonblob[i].PTy;
JFB.ms = jsonblob[i].PN;
var a = JSON.stringify(JFB)
payloadjson.push(a);
}
else {
JFB.ms = jsonblob[i].PN
JFB.srv = jsonblob[i].SA;
JFB.ptype = jsonblob[i].PTy;
var a = JSON.stringify(JFB)
payloadjson.push(a);
}
if ((payloadjson.length % 1500) == 0) {
console.log("Inside first loop---------counter--------- ", i );
var result = await update.invokeSDK("fnname", payloadjson, res)
payloadjson = [];
await sleepTime(20)
console.log("-----sleeped for 20ms----- ",i)
}
if (jsonblob.length == i + 1 && payloadjson.length > 0) {
var result = await update.invokeSDK("fnname", payloadjson, res)
payloadjson = [];
}
}
console.log("FRKNG Length _________i: ",i);
}
jsonResponse = { "failedRecords": "fail" }
return jsonResponse;
} catch (err) {
console.log('error:----', err);
return err;
}
}
I have a cloud function. It is triggered by an App Engine Cron job. It triggers my Firebase Cloud Function every hour with a Google Cloud Pub/Sub. I fetch my Firebase Realtime Database once, and loop for every value. The problem is my main.async function called multiple times. I use an i variable for loop and my console logs more i count than my database length. I mean that if my database length is 4, but for loop runs 8 or 15 or 23 times. This values change randomly. I want to loop for my each database value,fetch some data on internet,and when it is done, go for next value. Here is the code:
use strict';
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
var request = require('request-promise').defaults({ encoding: null });
var fs = require('fs');
// Get a reference to the Cloud Vision API component
const Vision = require('#google-cloud/vision');
const vision = new Vision.ImageAnnotatorClient();
var os = require("os");
var databaseArray = [];
var uniqueFilename = require('unique-filename')
exports.hourly_job = functions.pubsub
.topic('hourly-job')
.onPublish((event) => {
console.log("Hourly Job");
var db = admin.database();
var ref = db.ref("myData")
ref.once("value").then(function(allData) {
allData.forEach(function(deviceToken) {
deviceToken.forEach(function(firebaseIDs) {
var deviceTokenVar = deviceToken.key;
var firebaseIDVar = firebaseIDs.key;
var firstvalue = firebaseIDs.child("firstvalue").val();
var secondvalue = firebaseIDs.child("secondvalue").val();
var items = [deviceTokenVar, firebaseIDVar, firstvalue, secondvalue];
databaseArray.push(items);
});
});
return databaseArray;
}).then(function (databasem) {
main().catch(console.error);
});
return true;
});
const main = async () => {
var i;
for (i = 0; i < databaseArray.length; i++) {
console.log("Database Arrays " + i + ". elements: ");
if (databaseArrayfirst != "") {
var apiUrl = "http://api.blabla;
try {
const apiBody = await request.get(apiUrl);
///////////////////////////vison start//////////////////////
const visionResponseBody = await vision.documentTextDetection(apiBody)
var visionResponse = visionResponseBody[0].textAnnotations[0].description;
...some logic here about response...
/////////////////////////////////////////////////
var getdatabasevar = await admin.database().ref("myData/" + databaseArrayDeviceToken + "/" + databaseArrayFirebaseID);
await getdatabasevar.update({
"firstvalue": visionResponse
});
/////////////////////////////////////////////////
} catch (error) {
console.error(error);
}
///////////////////////////vison end//////////////////////
}
};
return true;
};
Thank you.
I develop for Firebase Cloud Functions. I have a Firebase Realtime Database like this:
----- myData
-------eqewrwrepere (this one is a device token)
---------Lta+sde-fer (this one is a firebase id)
firstvalue : "a"
secondvalue : "b"
----------Qrgd+ad-qdda (this one is second firebase id)
firstvalue : "c"
secondvalue : "d"
-------eqwerSAsdqe (this one is another device token)
---------Lta+sde-fer (this one is a firebase id)
firstvalue : "x"
secondvalue : "y"
----------Qrgd+ad-qdda (this one is second firebase id)
firstvalue : "z"
secondvalue : "t"
I fetch these data by this code. With this code i fetch all data and put them an array. And when fetching done, i loop this array for finding items. I am an iOS developer, so i am a newbie for NodeJS. Here is what i want to do:
Get firstvalue for each database data.
Make a api request with firstvalue of each database data.
Api returns an image.
Write image temp directory.
Process this image for visionApi.
Extract text.
Update database.
Send notification for deviceToken
Now i am able to retrieve database items in my array. When i make a request in for loop, request called async. So for loop continues, but request response or writing file and vision processing executed only once.
In for loop, get databasearray[0], make request, write file, process it with vision api, update database and go for next databasearray[1] item.
I read about Promises on different pages. But i did not understand.
Thank you.
'use strict';
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
var request = require('request');
var fs = require('fs');
//var fs = require("fs");
// Get a reference to the Cloud Vision API component
const Vision = require('#google-cloud/vision');
const vision = new Vision.ImageAnnotatorClient();
// Imports the Google Cloud client library
//const {Storage} = require('#google-cloud/storage');
var fs = require("fs");
var os = require("os");
var databaseArray = [];
exports.hourly_job = functions.pubsub
.topic('hourly-job')
.onPublish((event) => {
console.log("Hourly Job");
var db = admin.database();
var ref = db.ref("myData")
ref.once("value").then(function(allData) {
allData.forEach(function(deviceToken) {
deviceToken.forEach(function(firebaseIDs) {
var deviceTokenVar = deviceToken.key;
var firebaseIDVar = firebaseIDs.key;
var firstvalue = firebaseIDs.child("firstvalue").val();
var secondvalue = firebaseIDs.child("secondvalue").val();
var items = [deviceTokenVar, firebaseIDVar, firstvalue, secondvalue];
databaseArray.push([...items]);
});
});
return databaseArray;
}).then(function(databasem) {
var i;
for (i = 0; i < databaseArray.length; i++) {
var databaseArrayDeviceToken = databaseArray[i][0];
console.log("DeviceToken: " + databaseArrayDeviceToken);
var databaseArrayFirebaseID = databaseArray[i][1];
console.log("FirebaseID: " + databaseArrayFirebaseID);
var databaseArrayfirstvalue = databaseArray[i][2];
console.log("firstval: " + databaseArrayfirstvalue);
var databaseArraysecondval = databaseArray[i][3];
console.log("Second: " + databaseArraysecondval);
var url = "http://api.blabla" + databaseArrayfirstvalue;
/////////////here make a request, pause loop, process returned image, but how //////////////////////
request.get({
url: url,
encoding: 'binary'
}, function(error, httpResponse, body) {
if (!error && httpResponse.statusCode == 200) {
fs.writeFileSync('/tmp/processed.jpg', body, 'binary')
console.log("file written");
})
}
});
return true;
});
I found solution with Mocas helps. Here is the solution. I use async/await functions in code. Now for loop waits for the function response. But now I have different problems. I think main async function hangs because of awaits. And then next hourly trigger, it runs again. So console log shows 15-16-17 or more ‘i’ values in for loop. I have 4 element in database array but console log shows more than this every hour. And it increases every time. So I guess that I should cancel this await functions after a timeout. But I don’t know how. Here is code:
use strict';
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
var request = require('request-promise').defaults({ encoding: null });
var fs = require('fs');
// Get a reference to the Cloud Vision API component
const Vision = require('#google-cloud/vision');
const vision = new Vision.ImageAnnotatorClient();
var os = require("os");
var databaseArray = [];
var uniqueFilename = require('unique-filename')
exports.hourly_job = functions.pubsub
.topic('hourly-job')
.onPublish((event) => {
console.log("Hourly Job");
var db = admin.database();
var ref = db.ref("myData")
ref.once("value").then(function(allData) {
allData.forEach(function(deviceToken) {
deviceToken.forEach(function(firebaseIDs) {
var deviceTokenVar = deviceToken.key;
var firebaseIDVar = firebaseIDs.key;
var firstvalue = firebaseIDs.child("firstvalue").val();
var secondvalue = firebaseIDs.child("secondvalue").val();
var items = [deviceTokenVar, firebaseIDVar, firstvalue, secondvalue];
databaseArray.push([...items]);
//console.log(databaseArray);
//return true;
});
//return true;
});
return databaseArray;
}).then(function (databasem) {
main().catch(console.error);
});
return true;
});
const main = async () => {
var i;
for (i = 0; i < databaseArray.length; i++) {
console.log("Database Arrays " + i + ". elements: ");
var databaseArrayDeviceToken = databaseArray[i][0];
console.log("DeviceToken: " + databaseArrayDeviceToken);
var databaseArrayFirebaseID = databaseArray[i][1];
console.log("FirebaseID: " + databaseArrayFirebaseID);
var databaseArrayfirst = databaseArray[i][2];
console.log("first: " + databaseArrayfirst);
var databaseArraysecond = databaseArray[i][3];
console.log("second: " + databaseArraysecond);
if (databaseArrayfirst != "") {
var apiUrl = "http://api.blabla;
try {
const apiBody = await request.get(apiUrl);
///////////////////////////vison start//////////////////////
const visionResponseBody = await vision.documentTextDetection(apiBody)
var visionResponse = visionResponseBody[0].textAnnotations[0].description;
console.log("Vision response text " + visionResponse );
...some logic here about response...
/////////////////////////////////////////////////
var getdatabasevar = await admin.database().ref("myData/" + databaseArrayDeviceToken + "/" + databaseArrayFirebaseID);
await getdatabasevar.update({
"firstvalue": visionResponse
});
/////////////////////////////////////////////////
var getanotgerdatabasevar = await admin.database().ref("myData/" + databaseArrayDeviceToken + "/" + databaseArrayFirebaseID + "/" + "secondvalue");
await getanotgerdatabasevar.once("value")
.then(function(var) {
..some logic..
//send notification
});
} catch (error) {
console.error(error);
}
///////////////////////////vison end//////////////////////
}
};
return true;
};
I am using firebase for my android application and am performing full text search using Algolia which is suggested by all the blogs. I have successfully developed the script and its functioning properly. Now I want to host the script to run 24* 7. As I have an azure account , how do I go about uploading the script ? I have tried uploading the following as a function , web app but have been unsuccessful .
PS:- I have tried Heroku but wasn't satisfied.
The Script.
var http = require('http');
var port = process.env.port || 1337;
http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello World\n');
}).listen(port);
var dotenv = require('dotenv');
var firebaseAdmin = require("firebase-admin");
var algoliasearch = require('algoliasearch');
var algoliasearchHelper = require('algoliasearch-helper');
// load values from the .env file in this directory into process.env
dotenv.load();
// configure firebase
var serviceAccount = require("./serviceAccountKey.json");
firebaseAdmin.initializeApp({
credential: firebaseAdmin.credential.cert(serviceAccount),
databaseURL: process.env.FIREBASE_DATABASE_URL
});
var database = firebaseAdmin.database();
// configure algolia
var algolia = algoliasearch(process.env.ALGOLIA_APP_ID, process.env.ALGOLIA_API_KEY);
var index = algolia.initIndex('books');
var contactsRef = database.ref("/BookFair");
contactsRef.on('child_added', addOrUpdateIndexRecord);
contactsRef.on('child_changed', addOrUpdateIndexRecord);
contactsRef.on('child_removed', deleteIndexRecord);
function addOrUpdateIndexRecord(dataSnapshot) {
// Get Firebase object
var firebaseObject = dataSnapshot.val();
// Specify Algolia's objectID using the Firebase object key
firebaseObject.objectID = dataSnapshot.key;
// Add or update object
index.saveObject(firebaseObject, function(err, content) {
if (err) {
throw err;
}
console.log('Firebase object indexed in Algolia', firebaseObject.objectID);
});
}
function deleteIndexRecord(dataSnapshot) {
// Get Algolia's objectID from the Firebase object key
var objectID = dataSnapshot.key;
// Remove the object from Algolia
index.deleteObject(objectID, function(err, content) {
if (err) {
throw err;
}
console.log('Firebase object deleted from Algolia', objectID);
});
}
var queries = database.ref("/queries");
queries.on('child_added', addOrUpdateIndexRecordN);
function addOrUpdateIndexRecordN(dataSnapshot) {
// Get Firebase object
var firebaseObject = dataSnapshot.val();
// Specify Algolia's objectID using the Firebase object key
firebaseObject.objectID = dataSnapshot.key;
// Add or update object
var collegeName = "";
var query_ID_LOLWA= "";
var year="";
var query = "";
var counter = 0;
for(var i in firebaseObject){
var c = firebaseObject.charAt(i);
if(c=='/'){
counter = counter + 1;
continue;
}
else{
if(counter==2)
collegeName = collegeName + c;
else if(counter == 3)
year = year+c;
else if(counter == 1)
query_ID_LOLWA = query_ID_LOLWA + c;
else
query = query +c;
}
}
console.log(collegeName);
console.log(year);
console.log(query_ID_LOLWA);
console.log(query);
const query_final = query_ID_LOLWA;
var helper = algoliasearchHelper(algoliasearch("****", "****"), 'books', {
facets: ['collegeName', 'year','priority']});
helper.on('result', function(data,query_ID_LOLWA){
data.getFacetValues('priority',{sortBy: ['count:desc']});
console.log(data.hits);
var path_query = "/queries_answers/"+query_final;
path_query = path_query.toString();
console.log(path_query);
if(data.hits.length==0){
console.log("No results");
database.ref(path_query).push(-1);
}
else if(data.hits.length>1){
var ID = 1;
var counter = -1;
var length = data.hits.length-1;
for(var h in data.hits){
counter = counter + 1;
if( (counter%5 == 0) && (counter != 0)){
ID = ID + 1;
}
database.ref(path_query+"/"+ID).push(data.hits[h].uuid);
}
database.ref(path_query+"/totalResults").push(data.hits.length);
}
else{
database.ref(path_query+"/totalResults").push(data.hits.length);
for(var h in data.hits)
database.ref(path_query+"/1").push(data.hits[h].uuid);
}
});
helper.addFacetRefinement('collegeName', collegeName);
helper.addFacetRefinement('year',year);
helper.setQuery(query);
helper.search();
/*index.search(firebaseObject, function(err, content) {
if (err) {
console.error(err);
return;
}
console.log(content.hits);
for (var h in content.hits) {
console.log('Hit(' + content.hits[h].objectID + '): ' + content.hits[h].uuid);
}
database.ref("/query_result").push(content.hits);
});*/
}
Without more details than but have been unsuccessful, the only advice one could give you is to follow the usual steps to get a time-based Azure function deployed.
The simplest way is to use the Azure Portal:
Login to your Microsoft Azure account
Create a Function App to host your function
Add a Timer-triggered Function
Select the TimerTrigger-Javascript template to get started
At this point, you'll have a function that runs every minute. You can check the logs to confirm it is working.
You now want to configure its frequency:
Update the function's Timer Schedule (in the Integrate tab) to set how frequently the function should run
Finally, replace the template's code with your own.
You can find a detailed tutorial here with explanations on how to achieve each of these steps.