云函数
使用Cloud Functions for Firebase,您可以自动运行后端代码以响应由 Firebase 功能和 HTTPS 请求触发的事件。
如果您需要一个函数在调用时对数据库执行工作,您可以配置一个HTTP trigger 来执行此操作。例如,下面的云函数从数据库中读取最后存储的数字(存储在/lastNumber),将其加1(一),将其保存回数据库,然后返回当前值:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.nextNumber = functions.https.onRequest((req, res) => {
var ref = admin.database().ref('/lastNumber');
ref.transaction(function(current) {
return (current || 0) + 1;
}, function(error, committed, snapshot) {
var currentNumber = snapshot.val().toString();
console.log("Generated number: ", currentNumber);
res.status(200).send(currentNumber);
});
});
一旦deployed to Cloud Functions,您只需访问它的HTTPS端点即可调用此函数(其中<region>是您的地区,<project-id>是您的项目ID):
https://<region>-<project-id>.cloudfunctions.net/nextNumber
Firebase Functions Samples repository 上还有大量其他示例可供您浏览和使用。
实时数据库
Firebase 实时数据库称为NoSQL,这意味着没有直接关系或外键约束,因此建议您在存储数据时使用denormalization 的过程。
文档详细介绍了best practices for structuring your data,最重要的是避免嵌套数据,而是尽可能地使用flatten data structures 创建可扩展的数据。
这里的基本前提是,当您只需要获取选定数量的项目时,您希望避免从数据库中下载所有数据,但同样具有将项目链接在一起的能力,就像在关系数据库中一样。来自documentation on data fanout:
例如,考虑用户和组之间的双向关系。用户可以属于一个组,而组包含一个用户列表。当需要决定用户所属的组时,事情就变得复杂了。
需要一种优雅的方式来列出用户所属的组并仅获取这些组的数据。组索引在这里可以提供很大帮助:
// An index to track Ada's memberships
{
"users": {
"alovelace": {
"name": "Ada Lovelace",
// Index Ada's groups in her profile
"groups": {
// the value here doesn't matter, just that the key exists
"techpioneers": true,
"womentechmakers": true
}
},
...
},
"groups": {
"techpioneers": {
"name": "Historical Tech Pioneers",
"members": {
"alovelace": true,
"ghopper": true,
"eclarke": true
}
},
...
}
}
复制数据并使用此类索引是此类数据库的建议模式。这就是为什么有可用的函数允许您执行多位置写入以简化非规范化过程。
例如在Android中,使用上述数据库结构,您可以轻松插入一个新用户(用户名为testuser)并将其添加到techpioneers组in a single operation:
DatabaseReference database = FirebaseDatabase.getInstance().getReference();
HashMap<String, Object> data = new HashMap<>();
// Build the new data using location paths
data.put("/users/testuser/name", "Test User");
data.put("/users/testuser/groups/techpioneers", true)
data.put("/groups/techpioneers/members/testuser", true);
// Save this new data all at once
database.updateChildren(data);
Firebase 已发布多个samples, examples and code labs to help you get started。