如何读取RTDB随机生成的节点及其值?



下面是我的打字代码,它已经连接到电报,并设法发送消息。目前,我正试图通过阅读Arduino和MQ7创建的随机生成的节点并将其作为电报消息发送,从而对其进行更多的修补。

import * as functions from "firebase-functions";
import * as express from "express";
import * as cors from "cors";
import * as admin from "firebase-admin";
admin.initializeApp();
const bot = express();
bot.use(cors( {origin: true}));
bot.post("/", async function(req, res) {
const telegramText = req.body;
req.body.message &&
req.body.message.chat &&
req.body.message.chat.id &&
req.body.message.from &&
req.body.message.from.first_name;
if (telegramText) {
const chat_id = req.body.message.chat.id;
const first_name = req.body.message.from.first_name;
const receivedMessage = req.body.message.text;
//  Define your RTDB Reference
const rtdbReference = admin.database().ref("Sensor MQ7");
const mq7ref = rtdbReference.child("-NHi7dBPMlVi6hXrnI03");
const valref = mq7ref.child("MQ7");
//  Fetch the data
const snap = await valref.get();
const snapValue = snap.val();
//  Inject snapvalue in the response
return res.status(200).send({
method: "sendMessage",
chat_id,
text: `${first_name}n${receivedMessage}n${snapValue}`,
});
}
return res.status(200).send({status: "An error occured"});
});
export const router = functions.https.onRequest(bot);
我弄清楚了如何从数据库中读取条目并将其写入电报,以及学习了一些参考和函数。现在,我正试图弄清楚如何在创建新节点时输出值。新节点随机生成@ Arduino和mq7气体传感器。基本上,每当传感器检测到危险量的一氧化碳时,它就会将输入发送到firebase,并创建一个具有新值的新节点。我已经分类了父=传感器MQ7中间子节点="随机生成节点">最后一个子节点= MQ7

。非常感谢任何帮助、建议或推荐。请解释一下,就像我5岁一样,因为我这周才开始做所有的事情,我对云功能真的非常非常陌生。谢谢你!RTDB

打字代码(用于发送到Telegram)工作,现在我试图弄清楚如何从数据库中读取条目并写入它变成电报

在Cloud Function中,你需要使用Node.js Admin SDK来与Firebase服务交互。

下面是如何读取实时数据库中特定Reference的数据:

import * as functions from "firebase-functions";
import * as express from "express";
import * as cors from "cors";
import * as admin from 'firebase-admin';   <== NEW
admin.initializeApp();                     <== NEW
const bot = express();
bot.use(cors( {origin: true}));
bot.post("/", async function(req, res) {
const telegramText = req.body;
req.body.message &&
req.body.message.chat &&
req.body.message.chat.id &&
req.body.message.from &&
req.body.message.from.first_name;

if (telegramText) {
const chat_id = req.body.message.chat.id;
const first_name = req.body.message.from.first_name;
const receivedMessage = req.body.message.text;
//Define your RTDB Reference
const rtdbReference = admin.admin.database().ref('foo/bar');
// Fetch the date
const snap = await rtdbReference.get();
const snapValue = snap.val();
// Do whatever you need with snapValue to inject it in your response...
return res.status(200).send({
method: "sendMessage",
chat_id,
text: `Hello ${first_name}, n You sent us message: ${receivedMessage}`,
});
}
return res.status(200).send({status: "An error occured"});

});
export const router = functions.https.onRequest(bot);

相关内容

  • 没有找到相关文章

最新更新