跟随你的 cmets 更新:
您希望“使用 Cloud Functions 在实时数据库上创建、编辑、读取和删除”,如您的问题中所述,模仿客户端 SDK 的行为,但来自您控制的服务器.您应该使用直接从此服务器调用的一个或多个 Cloud Functions。最合适的(基于您的 cmets)是使用 HTTPS Cloud Function。
例如,您可以使用如下简单的 HTTPS 云函数来写入实时数据库的特定节点,如下所示:
exports.writeToNode = functions.https.onRequest((req, res) => {
cors(req, res, () => {
const dbNode = req.body.nodeRef;
const objToWrite = req.body.nodeValue;
return admin.database().ref(dbNode).push(objToWrite)
.then(() => {
return res.send("Node " + dbNode + " updated!");
})
.catch(err => {
//please watch the official video https://www.youtube.com/watch?v=7IkUgCLr5oA&t=1s&list=PLl-K7zZEsYLkPZHe41m4jfAxUi0JjLgSM&index=3
});
});
});
您可以通过向以下 URL https://us-central1-YOURPROJECTID.cloudfunctions.net/writeToNode 发出 POST 来调用它,正文如下:
{
nodeRef: 'theNode',
nodeValue: {
firstName: 'John',
lastName: 'Doe'
}
}
初始化 Admin SDK:
如果您想通过 Cloud Function 与同一 Firebase 项目中的实时数据库进行交互,您只需初始化不带任何参数的 Admin SDK(即admin.initializeApp();)
这样,Admin SDK 将使用项目的默认服务帐户,并拥有对实时数据库的完全访问权限(即绕过所有安全规则)。
所以,初始化如下:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
/////额外的想法/////
请注意,您可以使用实时数据库公开的 REST API,而不是通过 Cloud Functions 开发一整套 CRUD 端点。见https://firebase.google.com/docs/database/rest/start
初始答案的剩余部分内容,关于背景触发的云函数
然后您需要声明一个云函数,如下例所示,通过:
- 选择一个“event handler”;
- 指定它将侦听事件的数据库路径;
- 执行所需的逻辑(通常使用路径上写入的数据,或者指示节点被删除等...)
exports.makeUppercase = functions.database.ref('/devices/{pushId}/original')
.onCreate((snapshot, context) => {
// Grab the current value of what was written to the Realtime Database.
const original = snapshot.val();
console.log('Uppercasing', context.params.pushId, original);
const uppercase = original.toUpperCase();
// You must return a Promise when performing asynchronous tasks inside a Functions such as
// writing to the Firebase Realtime Database.
// Setting an "uppercase" sibling in the Realtime Database returns a Promise.
return snapshot.ref.parent.child('uppercase').set(uppercase);
});
从documentation 复制的这段代码 sn-p 将侦听在devices 节点下创建的任何新节点,并将创建一个uppercase 节点,original 节点的值以大写形式显示。
请注意,这是一个后台触发的云函数,当特定路径“发生”某些事情时触发。
如果您想“在实时数据库上创建、编辑、读取和删除”,如您的问题中所述,模仿客户端 SDK 的行为,您可以定义一个或多个 Cloud Functions您直接从您的应用程序调用。请参阅 Callable Cloud Functions documentation。
您还可以阅读以下文档项目https://firebase.google.com/docs/functions/get-started 和https://firebase.google.com/docs/functions/database-events 并观看视频系列:https://firebase.google.com/docs/functions/video-series