以编程方式更改默认 Firebase 数据库,并在默认数据库和辅助数据库上运行相同的 Firebase 函数



>背景 - 我正在设置一项新功能,允许用户选择他们所在的城市,因为我的应用程序是一个公共交通应用程序。我希望城市位于单独的数据库中,为此,我在我的Firebase项目中创建了一个辅助数据库。这是一个 React Native 应用程序,我正在使用 react-native-firebase。

问题 1 - 当用户选择不同的城市时,我希望该数据库成为他的默认数据库。我不知道该怎么做,有人可以帮忙吗?

我尝试初始化并仅更改数据库URL,即使我连接到第二个数据库一次,它也不是每次都这样做。似乎是一个不稳定的解决方案。

我发现的另一个解决方案是将网址传递给每个"firebase.database(url)",但这似乎是一个糟糕的解决方案。

问题2 - 由于应用程序在两个城市完全相同,因此我想在 DB2 上运行我已经在 DB1 上运行的相同功能。它们是完全独立的数据库,但具有完全相同的节点。例如,两者都有一个"位置"节点,然后我有一个侦听器来进行更改。如何仅使用一个函数在两个数据库上设置侦听器?还是我需要获取对 DB2 的引用并复制函数?

没有每个用户的默认数据库的概念。这意味着您需要从 JavaScript 代码初始化 Firebase,如 React Native Firebase 文档所示:

// pluck values from your `GoogleService-Info.plist` you created on the firebase console
const iosConfig = {
clientId: 'x',
appId: 'x',
apiKey: 'x',
databaseURL: 'x',
storageBucket: 'x',
messagingSenderId: 'x',
projectId: 'x',
// enable persistence by adding the below flag
persistence: true,
};
// pluck values from your `google-services.json` file you created on the firebase console
const androidConfig = {
clientId: 'x',
appId: 'x',
apiKey: 'x',
databaseURL: 'x',
storageBucket: 'x',
messagingSenderId: 'x',
projectId: 'x',
// enable persistence by adding the below flag
persistence: true,
};
const kittensApp = firebase.initializeApp(
// use platform specific firebase config
Platform.OS === 'ios' ? iosConfig : androidConfig,
// name of this app
'kittens',
);
// dynamically created apps aren't available immediately due to the
// asynchronous nature of react native bridging, therefore you must
// wait for an `onReady` state before calling any modules/methods
// otherwise you will most likely run into `app not initialized` exceptions
kittensApp.onReady().then((app) => {
// --- ready ---
// use `app` arg, kittensApp var or `app('kittens')` to access modules
// and their methods. e.g:
firebase.app('kittens').auth().signInAnonymously().then((user) => {
console.log('kittensApp user ->', user.toJSON());
});
});

最新更新