Skip to content

Commit 487f8e1

Browse files
authored
Fix multiple database instances when using emulator (#4247)
1 parent d638a42 commit 487f8e1

File tree

3 files changed

+32
-1
lines changed

3 files changed

+32
-1
lines changed

.changeset/dirty-hotels-cheat.md

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@firebase/database': patch
3+
---
4+
5+
Fix issue with multiple database instances when using Realtime Database emulator (#3681)

packages/database/src/core/RepoInfo.ts

+5-1
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,10 @@ export class RepoInfo {
128128

129129
/** @return {string} */
130130
toURLString(): string {
131-
return (this.secure ? 'https://' : 'http://') + this.host;
131+
const protocol = this.secure ? 'https://' : 'http://';
132+
const query = this.includeNamespaceInQueryParams
133+
? `?ns=${this.namespace}`
134+
: '';
135+
return `${protocol}${this.host}/${query}`;
132136
}
133137
}

packages/database/test/database.test.ts

+22
Original file line numberDiff line numberDiff line change
@@ -149,13 +149,35 @@ describe('Database Tests', () => {
149149
expect(db2.ref().toString()).to.equal('https://foo2.bar.com/');
150150
});
151151

152+
it('Different instances for different URLs (with FIREBASE_DATABASE_EMULATOR_HOST)', () => {
153+
process.env['FIREBASE_DATABASE_EMULATOR_HOST'] = 'localhost:9000';
154+
const db1 = defaultApp.database('http://foo1.bar.com');
155+
const db2 = defaultApp.database('http://foo2.bar.com');
156+
expect(db1.repo_.repoInfo_.toURLString()).to.equal(
157+
'http://localhost:9000/?ns=foo1'
158+
);
159+
expect(db2.repo_.repoInfo_.toURLString()).to.equal(
160+
'http://localhost:9000/?ns=foo2'
161+
);
162+
delete process.env['FIREBASE_DATABASE_EMULATOR_HOST'];
163+
});
164+
152165
it('Cannot use same URL twice', () => {
153166
defaultApp.database('http://foo.bar.com');
154167
expect(() => {
155168
defaultApp.database('http://foo.bar.com/');
156169
}).to.throw(/Database initialized multiple times/i);
157170
});
158171

172+
it('Cannot use same URL twice (with FIREBASE_DATABASE_EMULATOR_HOST)', () => {
173+
process.env['FIREBASE_DATABASE_EMULATOR_HOST'] = 'localhost:9000';
174+
defaultApp.database('http://foo.bar.com');
175+
expect(() => {
176+
defaultApp.database('http://foo.bar.com/');
177+
}).to.throw(/Database initialized multiple times/i);
178+
delete process.env['FIREBASE_DATABASE_EMULATOR_HOST'];
179+
});
180+
159181
it('Databases with legacy domain', () => {
160182
expect(() => {
161183
defaultApp.database('http://foo.firebase.com/');

0 commit comments

Comments
 (0)