Skip to content

Commit ab3ae2a

Browse files
authored
Fix issues with .ref in Database functions (#727)
1 parent b6e611b commit ab3ae2a

File tree

2 files changed

+21
-5
lines changed

2 files changed

+21
-5
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
11
- Fixes error when last argument to logger methods is `null`. (#716)
22
- Adds newly available locations `us-west3`, `europe-west6`, `northamerica-northeast1`, and `australia-southeast1`.
33
- No longer throw errors for unrecognized regions (deploy will error instead).
4+
- Fixes error where `snap.ref` in database functions did not work when using the Emulator Suite (#726)

src/providers/database.ts

Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ export const provider = 'google.firebase.database';
4141
export const service = 'firebaseio.com';
4242

4343
const databaseURLRegex = new RegExp('^https://([^.]+).');
44+
const emulatorDatabaseURLRegex = new RegExp('^http://.*ns=([^&]+)');
4445

4546
/**
4647
* Registers a function that triggers on events from a specific
@@ -138,14 +139,25 @@ export function _refWithOptions(
138139
'\n If you are unit testing, please set process.env.FIREBASE_CONFIG'
139140
);
140141
}
141-
const match = databaseURL.match(databaseURLRegex);
142-
if (!match) {
142+
143+
let instance = undefined;
144+
const prodMatch = databaseURL.match(databaseURLRegex);
145+
if (prodMatch) {
146+
instance = prodMatch[1];
147+
} else {
148+
const emulatorMatch = databaseURL.match(emulatorDatabaseURLRegex);
149+
if (emulatorMatch) {
150+
instance = emulatorMatch[1];
151+
}
152+
}
153+
154+
if (!instance) {
143155
throw new Error(
144156
'Invalid value for config firebase.databaseURL: ' + databaseURL
145157
);
146158
}
147-
const subdomain = match[1];
148-
return `projects/_/instances/${subdomain}/refs/${normalized}`;
159+
160+
return `projects/_/instances/${instance}/refs/${normalized}`;
149161
};
150162

151163
return new RefBuilder(apps(), resourceGetter, options);
@@ -350,7 +362,10 @@ export class DataSnapshot {
350362
private app?: firebase.app.App,
351363
instance?: string
352364
) {
353-
if (instance) {
365+
if (app && app.options.databaseURL.startsWith('http:')) {
366+
// In this case we're dealing with an emulator
367+
this.instance = app.options.databaseURL;
368+
} else if (instance) {
354369
// SDK always supplies instance, but user's unit tests may not
355370
this.instance = instance;
356371
} else if (app) {

0 commit comments

Comments
 (0)