如何从实时数据库(Firebase)获取 json 格式的数据?

How to fetch data in json format from realtime-database (Firebase)?

我正在尝试在我的应用程序中创建一个搜索功能,该功能基本上根据用户的查询过滤 json 数据(例如 产品列表 )(像任何产品名称)并显示最接近的结果。我已经成功地实现了这个搜索栏和过滤逻辑,但它正在处理我的应用程序中 产品列表 的本地 json 数据。我想要的是从网络调用(http 调用)中获取 json 数据,然后对其进行过滤。 但是我的实时数据库中有数据,但我不知道如何以 json 格式检索它们。我可以将云函数(节点 js)设置为 return 将 json 数据发送给客户端,但我不确定云函数中的逻辑应该是什么以将其连接到实时数据库和 return 回应

我在 Firebase 中的数据

现在如何通过云功能从我的应用程序中获取这些数据?

I am not sure about what should be the logic in the cloud functions to connect it to realtime-database and return the response. .... how can I fetch this data from my app through the cloud functions ?

我知道您想使用 HTTPS Cloud Function 作为 REST API 端点(您写道“我想要的是从网络调用中获取 json 数据(http 调用)").

您可以按照以下几行编写云函数:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();

exports.getRTDBData = functions.https.onRequest(async (req, res) => {
  
    const rtdbRootRef = admin.database().ref();

    const noticesDataSnapshot = await rtdbRootRef.child('notices').get();

    res.status(200).send(noticesDataSnapshot.val());   

});

使用 http 调用调用此 HTTPS 云函数时,您将获得整个 noticesRTDB 节点。如有必要,您可以调整 RTDB 查询,例如通过过滤数据,如 doc.

中所述

此外,我建议您观看此 video 以了解有关如何处理 HTTPS 云功能中的错误的更多信息。