diff --git a/.changeset/great-dolphins-tie.md b/.changeset/great-dolphins-tie.md new file mode 100644 index 00000000000..d6413844bfb --- /dev/null +++ b/.changeset/great-dolphins-tie.md @@ -0,0 +1,5 @@ +--- +"@firebase/database": patch +--- + +The SDK can now infer a default database URL if none is provided in the config. diff --git a/packages/database/src/core/RepoManager.ts b/packages/database/src/core/RepoManager.ts index 5ec5e7bc753..a8d8032684e 100644 --- a/packages/database/src/core/RepoManager.ts +++ b/packages/database/src/core/RepoManager.ts @@ -18,7 +18,7 @@ import { FirebaseApp } from '@firebase/app-types'; import { safeGet, CONSTANTS } from '@firebase/util'; import { Repo } from './Repo'; -import { fatal } from './util/util'; +import { fatal, log } from './util/util'; import { parseRepoInfo } from './util/libs/parser'; import { validateUrl } from './util/validation'; import './Repo_transaction'; @@ -32,9 +32,6 @@ import { FirebaseAuthTokenProvider } from './AuthTokenProvider'; -/** @const {string} */ -const DATABASE_URL_OPTION = 'databaseURL'; - /** * This variable is also defined in the firebase node.js admin SDK. Before * modifying this definition, consult the definition in: @@ -101,13 +98,17 @@ export class RepoManager { authProvider: Provider, url?: string ): Database { - let dbUrl: string | undefined = url || app.options[DATABASE_URL_OPTION]; + let dbUrl: string | undefined = url || app.options.databaseURL; if (dbUrl === undefined) { - fatal( - "Can't determine Firebase Database URL. Be sure to include " + - DATABASE_URL_OPTION + - ' option when calling firebase.initializeApp().' - ); + if (!app.options.projectId) { + fatal( + "Can't determine Firebase Database URL. Be sure to include " + + ' a Project ID when calling firebase.initializeApp().' + ); + } + + log('Using default host for project ', app.options.projectId); + dbUrl = `${app.options.projectId}-default-rtdb.firebaseio.com`; } let parsedUrl = parseRepoInfo(dbUrl); diff --git a/packages/database/test/database.test.ts b/packages/database/test/database.test.ts index 1187032eb32..67dc3653462 100644 --- a/packages/database/test/database.test.ts +++ b/packages/database/test/database.test.ts @@ -105,6 +105,20 @@ describe('Database Tests', () => { expect(db.ref().toString()).to.equal('https://localhost/'); }); + it('Can infer database URL from project Id', async () => { + const app = firebase.initializeApp( + { projectId: 'abc123' }, + 'project-id-app' + ); + const db = app.database(); + expect(db).to.be.ok; + // The URL is assumed to be secure if no port is specified. + expect(db.ref().toString()).to.equal( + 'https://abc123-default-rtdb.firebaseio.com/' + ); + await app.delete(); + }); + it('Can read ns query param', () => { const db = defaultApp.database('http://localhost:80/?ns=foo&unused=true'); expect(db).to.be.ok;