All files / src/utils firebase.js

100% Statements 24/24
100% Branches 12/12
100% Functions 1/1
100% Lines 24/24

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60                13x     13x     15x 5x 5x 5x         13x   13x 12x   4x         8x   1x     1x   7x       7x 3x 3x     7x       12x 12x 12x 12x 12x   12x  
/**
 * Firebase Admin SDK initialization.
 *
 * Provides shared instances of Firestore, Auth, RTDB, and Messaging.
 * Expects GOOGLE_APPLICATION_CREDENTIALS env var pointing to service account JSON,
 * or FIREBASE_SERVICE_ACCOUNT_PATH for explicit path.
 */
 
const admin = require('firebase-admin');
 
const serviceAccountPath =
  process.env.FIREBASE_SERVICE_ACCOUNT_PATH || process.env.GOOGLE_APPLICATION_CREDENTIALS;
 
function configureLocalEmulators() {
  if (process.env.NODE_ENV === 'local') {
    process.env.FIRESTORE_EMULATOR_HOST = 'localhost:8080';
    process.env.FIREBASE_AUTH_EMULATOR_HOST = 'localhost:9099';
    process.env.FIREBASE_DATABASE_EMULATOR_HOST = 'localhost:9000';
  }
}
 
// Configure emulators before any Firebase calls
configureLocalEmulators();
 
if (!admin.apps.length) {
  if (process.env.NODE_ENV === 'local') {
    // Emulators need a databaseURL for RTDB even though traffic goes to emulator
    admin.initializeApp({
      projectId: 'demo-shytalk',
      databaseURL: 'http://localhost:9000?ns=demo-shytalk-default-rtdb',
    });
  } else {
    if (!process.env.FIREBASE_DATABASE_URL) {
      // eslint-disable-next-line no-console
      console.error(
        'FIREBASE_DATABASE_URL env var is required (RTDB region differs between dev and prod)',
      );
      process.exit(1);
    }
    const initOptions = {
      databaseURL: process.env.FIREBASE_DATABASE_URL,
    };
 
    if (serviceAccountPath) {
      const serviceAccount = require(serviceAccountPath);
      initOptions.credential = admin.credential.cert(serviceAccount);
    }
 
    admin.initializeApp(initOptions);
  }
}
 
const db = admin.firestore();
const auth = admin.auth();
const rtdb = admin.database();
const messaging = admin.messaging();
const { FieldValue } = admin.firestore;
 
module.exports = { admin, db, auth, rtdb, messaging, FieldValue, configureLocalEmulators };