Firebase Cloud Functions部署失败问题排查与解决
Firebase Cloud Functions定时函数部署失败问题解决
我在使用Firebase Cloud Functions时,创建了一个每2小时运行的fetchNewsScheduled定时函数,该函数执行以下操作:
- 调用
clearNewsCollection函数清空news集合以释放数据库空间 - 从第三方API拉取新闻数据并写入Firebase数据库
但部署时出现错误:更新us-central1区域的fetchNewsScheduled函数失败。
相关代码如下:
type ArticleType = { _type: string; name: string; url: string; image: { _type: string; thumbnail: { _type: string; contentUrl: string; width: number; height: number; }; isLicensed: boolean; }; description: string; datePublished: string; }; type SimplifiedArticleType = { name: string; url: string; imageUrl: string; description: string; datePublished: string; };
async function clearNewsCollection() { const snapshot = await db.collection("news").get(); const batch = db.batch(); snapshot.forEach((doc) => { batch.delete(doc.ref); }); await batch.commit(); console.log(`Deleted ${snapshot.size} documents from`); }
async function fetchNews() { const options = { method: "GET", url: "https://bing-news-search1.p.rapidapi.com/news", params: { safeSearch: "Off", textFormat: "Raw" }, headers: { "X-BingApis-SDK": "true", "X-RapidAPI-Key": "my_key", "X-RapidAPI-Host": "bing-news-search1.p.rapidapi.com", }, }; try { await clearNewsCollection(); const response = await axios.request(options); const newsArticles = response.data.value; //an array const simplifiedArticles = newsArticles.map((article: ArticleType) => { return { name: article.name, url: article.url, imageUrl: article.image?.thumbnail?.contentUrl, description: article.description, datePublished: article.datePublished, //eg. "2023-03-10T14:31:02.0000000Z", moment(datePublished).fromNow(); }; }); const batch = db.batch(); simplifiedArticles.forEach((article: SimplifiedArticleType) => { const docRef = db.collection("news").doc(); batch.set(docRef, article); }); await batch.commit(); console.log("Batch write successful"); } catch (error) { console.log("Error writing documents:", error); } }
// Define the Cloud Function to run every 2 hours export const fetchNewsScheduled = functions.pubsub .schedule("every 2 hours") .onRun(async (context) => { await fetchNews(); return null; });
解决方案
排查后发现两处疏忽性错误:
- axios安装路径错误:需进入
my-app/functions目录执行npm install axios,而非项目根目录,否则函数运行时会找不到axios依赖 - Firebase数据库不允许存储undefined值:API返回的部分字段可能为null或undefined,直接写入会导致批量提交失败
给后续开发者的提示
- 检查
functions目录下的package.json,确认依赖是否正确安装并添加到依赖列表中 - 绝对不能在Firebase数据库中存储undefined值,需提前为可能为空的字段设置默认值(如空字符串)
修改后的关键代码片段:
const simplifiedArticles = newsArticles.map((article: ArticleType) => { return { name: article.name || "", url: article.url || "", imageUrl: article.image?.thumbnail?.contentUrl || "", description: article.description || "", datePublished: article.datePublished || "", //eg. "2023-03-10T14:31:02.0000000Z", moment(datePublished).fromNow(); }; });
内容的提问来源于stack exchange,提问作者Tom Fan
相关产品推荐
相关产品推荐

