【发布时间】:2020-07-22 13:21:54
【问题描述】:
我有一个 React Web 应用程序,它使用 Firestore 作为其数据库,每个 Firestore 集合有多个 (10+) Firebase 函数,用于发布到社交媒体等副作用:
exports.onUserSignUp = functions.auth.user().onCreate(user => {
// Insert into users collection
// Insert into profiles collection
// Notify via Discord webhook
// insert into history collection to keep track of actions performed by users
})
exports.onCityCreate = functions.firestore.document('cities/{cityId}').onCreate(doc => {
// Notify via Discord webhook
// Send tweet
// Update cache in a collection
// Insert into history collection to keep track of actions performed by users
})
等等
在 Firebase 函数教程中,他们经常建议您声明一个 Firebase 函数以获得这样的副作用:
exports.onCityCreate = functions.firestore.document('/cities/{documentId}')
.onCreate((snap, context) => {
...
})
如果您有一个小的副作用,这是有道理的 - 例如。通过 Twitter REST API 发送推文 - 但随着时间的推移,我添加了越来越多的副作用,例如通过 webhook 发送到 Discord、将新记录插入其他数据库、缓存数据等等。
当我在 AWS 中了解 lambda 时,我被教导要使我的函数变得很小,并且仅限于一项工作,而不是 1 个大型函数。这意味着如果一种副作用失败,它不会降低其他副作用。它使代码更容易理解和阅读。它使调试更容易。
所以上面的函数可以拆分到每个作业:
exports.sendTweetOnCityCreate = functions.firestore.document('cities/{cityId}').onCreate(doc => {
// send tweet via REST API
})
exports.sendDiscordOnCityCreate = functions.firestore.document('cities/{cityId}').onCreate(doc => {
// send Discord message via webhook
})
exports.updateCitiesCache = functions.firestore.document('cities/{cityId}').onCreate(doc => {
// update a record in a cache collection with some kind of tally etc.
})
exports.recordCityInHistory = functions.firestore.document('cities/{cityId}').onCreate(doc => {
// insert into history collection to keep track of actions performed by users
})
为每个副作用声明一个小的、独立的函数而不是像我目前拥有的那样“完成所有”的 1 个大型函数,是否会受到惩罚(性能 - 速度较慢或财务 - 来自 Google 的更多成本)?强>
【问题讨论】:
标签: firebase google-cloud-functions