I have a node.js script that works perfectly when running from command line, but when I try to use it as a function fails.
const functions = require('firebase-functions');
exports.dailyUpdate = functions.pubsub.schedule('5 5 * * *')
.onRun((context) => {
db.collection("meters")
.get()
.then(function (querySnapshot) {
querySnapshot.forEach(function (doc) {
let mtrList = meterlist.push([
doc.id,
]);
return true;
});
meterlist
.forEach(function (obj) {
var meterid = obj[0];
var meterdata;
var history = [];
axios
.get(url)
.then((response) => {
metername = meterid.toString();
meterdata = response.data.meterdata;
if (meterdata) {
meterdata.forEach(function (obj) {
let datadate = obj.stamp.substring(0, 10);
let datatime = obj.stamp.substring(11, 13);
let data = obj.data;
history.push({
metername: metername,
datadate: datadate,
datatime: datatime,
data: data,
});
});
let todayUpdate = runCalculations(history);
updateDB(todayUpdate);
}
return Promise.resolve("done!");
})
.catch(function (error) {
console.log(error);
});
return true;
})
return true;
})
.catch(function (error) {
console.log(error);
});
response.send("Updated!!");
});
I'm sure I'm doing something wrong, but when I, for example put the requires in the code section,
const axios = require("axios");
const firebase = require("firebase");
require("firebase/firestore");
var moment = require("moment");
var _ = require("lodash");
var Promise = require("promise");
doesn't run because it doesn't know where axios is. When I place them before the exports... below the const functions = require('firebase-functions'); I get different errors, including: ""Detailed stack trace: Error: Cannot find module 'axios'" // Provided module can't be loaded. // Could not load the function, shutting down. // Function cannot be initialized. "
The script itself runs a querySnapshot from a Firestore db, parses the results, calls an api through axios, runs a bunch of calculations, and then updates the db with the updated results. And I want this to run at 5:05AM every day.
I did not make any changes to the actual code of the script besides including the above exports code.
What am I missing?