我写了一个Firebase云函数来从外部api获取数据并读/写到Firestore。我多次使用“ firebase服务”在本地运行该功能。然后我注意到,即使没有调用该功能,每小时也要进行约500次Firestore API调用。而Firestore的写入和删除保持为0,只有读取增加。
仅当我关闭计算机时,读峰值才会停止,因此我相信是云功能造成的。
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const axios = require('axios');
admin.initializeApp();
exports.someFunc = functions.https.onRequest((request, response) => {
const url = 'https://someurl.com';
const getData = async url => {
try {
const response = await axios.get(url);
const data = response.data;
if (data.status === 'ok') {
data.articles.forEach(element => {
if (element.author) {
element.author = element.author.replace(/\//g, ',');
var authorRef = admin
.firestore()
.collection('authors')
.doc(element.author);
authorRef
.get()
.then(doc => {
if (!doc.exists) {
authorRef.set({
sources: [element.source.name]
});
} else {
var sources = doc.data().sources;
if (!sources.includes(element.source.name)) {
sources.push(element.source.name);
authorRef.update({
sources: sources
});
}
}
return null;
})
.catch(error => {
console.log('Error getting document:', error);
});
}
if (element.source.name) {
element.source.name = element.source.name.replace(/\//g, ',');
var sourceRef = admin
.firestore()
.collection('sources')
.doc(element.source.name);
sourceRef
.get()
.then(doc => {
if (!doc.exists) {
var sourceUrl = 'https://' + element.url.split('/')[2];
sourceRef.set({
sourceUrl: sourceUrl
});
}
return null;
})
.catch(error => {
console.log('Error getting document:', error);
});
}
admin
.firestore()
.collection('articles')
.add(element);
});
}
} catch (error) {
console.log(error);
}
};
getData(url);
response.send('Success!');
});
“作者”,“来源”和“文章”集合每个最多只有20个文档,因此必须有一些东西反复调用Firestore,但我找不到。
答案 0 :(得分:0)
尽管这似乎是一个定价问题,但我认为这可能是Cloud Functions Retries的问题,而且您的使用次数与代码不匹配,因为您有设置和更新方法至少写一次。您可能要检查函数是否成功执行。
如果您想了解Firestore的定价,这可能会有所帮助。
Firebase Firestore读取基于许多参数,例如
您可以找到详细的说明here
和更多示例here