Firebase:如何从外部数据库读取? [英] Firebase: How to read from external DB?

查看:150
本文介绍了Firebase:如何从外部数据库读取?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在另一台服务器上的PostgreSQL中有一些数据,需要读取这些数据以包含在Firebase应用程序中,然后呈现图表。我只有db连接字符串,没有端点可以返回该数据。

I have some data in PostgreSQL on another server that I need to read to include in my Firebase app, and then render charts. I only have the db connection string, there are no endpoints there to return that data.


  • 我将输入连接字符串限制为管理员,在Firebase上使用auth和角色。

  • I would restrict entering connection string to admin, using auth and roles on Firebase.

然后我需要一种方法让Firebase应用程序使用SQL捕获数据并在客户端上显示,这将呈现表和图表。

Then I need a way for Firebase app to grab that data with SQL and show on client, which would render tables and charts.

即使在网络流量中,用户也永远无法看到连接字符串。

The user should never be able to see the connection strings, even in network traffic.

这可行吗?

推荐答案

我有一个类似的问题要解决作为临时解决方案,我使用firebase admin serviceAccount初始化了应用。然后在服务器上侦听firebase集合的更改,并在插入的新值上侦听\更新PostgreSQL中的值。

I had a similar problem to solve and as a temporary solution I initialized app with firebase admin serviceAccount. Then listened for changes of firebase collection on my server and on new value received inserted\updated the values in PostgreSQL.

以admin身份初始化应用程序,并在firebase上侦听更改:

Initialize app as admin and listen for changes on firebase:

  admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
    databaseURL: 'https://yourfirebaseproject.firebaseio.com',
  });

  const db = admin.database();

  db.ref('User').on('value', async (snapshot) => {
    insertOrUpdate(User, 'users', snapshot.val());
  });

在PostgreSQL中插入更新数据:

Insert\update data into PostgreSQL:

const insertOrUpdate = (model, tableName, data) => {
  const firstData = data[0] ? data[0] : data;

  return model.knex().raw(
    knex(tableName).insert(data).toQuery() + ' ON CONFLICT ("id") DO UPDATE SET ' +
      Object.keys(firstData).map((field) => `${field}=EXCLUDED.${field}`).join(', ')
  );
};

这篇关于Firebase:如何从外部数据库读取?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆