Using three functions (getViews, getViewCount and updateCount) I want to retrieve a youtube view count and then store it in a firestore database. Both functions work asynchronously, but when I call getViews() inside updateCount() I get the following error within updateCount:
TypeError: Cannot read properties of undefined (reading 'on') which refers to a promise.
Please let me know am I doing wrong here! Code below:
getViews:
exports.getViews = functions
.runWith({
secrets: ["YOUTUBE_API"]
})
.https.onCall(async (data, context) => {
const count = await getViewCount({});
return count;
});
updateCount:
exports.updateCount = functions.https.onRequest(async (req, res) => {
const viewData = await this.getViews({ "h": "j" }); //Error occurs here
const addData = await admin
.firestore()
.collection("viewCount")
.doc("Count")
.set(viewData)
.then(() => {
console.log("Document successfully written!");
})
.catch((error) => {
console.error("Error writing document: ", error);
});
});
getViewCount:
const getViewCount = async (arg) => {
const youtube = google.youtube({
version: "v3",
auth: process.env.YOUTUBE_API,
});
const count = await youtube.channels.list({
id: process.env.YOUTUBE_CHANNEL_ID,
part: "statistics",
});
const countData = count.data.items[0].statistics.viewCount;
return countData;
}
CodePudding user response:
If you want to use the code in getViews()
Cloud Function as well, then it might be better to move that to a different function. Try refactoring the code as shown below:
exports.getViews = functions
.runWith({
secrets: ["YOUTUBE_API"]
})
.https.onCall(async (data, context) => {
const count = await getViewCount({}); // <-- pass required arguments
return count;
})
exports.updateCount = functions.https.onRequest(async (req, res) => {
const viewData = await getViewCount({ "h": "j" });
const addData = await admin
.firestore()
.collection("viewCount")
.doc("Count")
.set(viewData)
.then(() => {
console.log("Document successfully written!");
})
.catch((error) => {
console.error("Error writing document: ", error);
});
});
// not a Cloud Function
const getViewCount = async (arg) => {
const youtube = google.youtube({
version: "v3",
auth: process.env.YOUTUBE_API,
});
const count = await youtube.channels.list({
id: process.env.YOUTUBE_CHANNEL_ID,
part: "statistics",
});
const countData = count.data.items[0].statistics.viewCount;
return countData;
}