Prof_app / src /config /firebase.js
Huzaifa1435's picture
Initial Commit: Clean backend without large files
e3fefe8
Raw History Blame Contribute Delete
5.02 kB
const admin = require('firebase-admin');
const path = require('path');
const fs = require('fs');
let db;
// Initialize Firebase Admin only once
if (!admin.apps.length) {
// Try to get path from environment variable, otherwise use default
let serviceAccountPath = process.env.FIREBASE_SERVICE_ACCOUNT_PATH;
if (!serviceAccountPath) {
// Try multiple possible locations
const possiblePaths = [
path.resolve(__dirname, './serviceAccountKey.json'),
path.resolve(__dirname, '../config/serviceAccountKey.json'),
path.resolve(process.cwd(), './src/config/serviceAccountKey.json'),
path.resolve(process.cwd(), './serviceAccountKey.json'),
];
for (const possiblePath of possiblePaths) {
if (fs.existsSync(possiblePath)) {
serviceAccountPath = possiblePath;
break;
}
}
}
// Final check
if (!serviceAccountPath || !fs.existsSync(serviceAccountPath)) {
console.error('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
console.error('❌ FIREBASE SERVICE ACCOUNT KEY NOT FOUND!');
console.error(` Expected at: ${serviceAccountPath || 'src/config/serviceAccountKey.json'}`);
console.error('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
process.exit(1);
}
console.log(`πŸ“ Loading service account from: ${serviceAccountPath}`);
// Load service account JSON
const serviceAccount = require(serviceAccountPath);
// Initialize Firebase Admin
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: process.env.FIREBASE_DATABASE_URL || 'https://serviceconnect-dea35-default-rtdb.firebaseio.com/',
});
console.log('βœ… Firebase Admin (Realtime Database) initialized successfully');
}
// Realtime Database reference
db = admin.database();
const auth = admin.auth();
const messaging = admin.messaging();
// ─── Realtime Database Helpers ────────────────────────────────────────────────
/**
* Get value at a path
*/
async function dbGet(path) {
try {
const snap = await db.ref(path).once('value');
return snap.exists() ? snap.val() : null;
} catch (error) {
console.error(`❌ dbGet error at ${path}:`, error.message);
return null;
}
}
/**
* Set value at a path (overwrites)
*/
async function dbSet(path, data) {
try {
await db.ref(path).set({ ...data, _updatedAt: Date.now() });
return true;
} catch (error) {
console.error(`❌ dbSet error at ${path}:`, error.message);
return false;
}
}
/**
* Update (merge) value at a path
*/
async function dbUpdate(path, data) {
try {
await db.ref(path).update({ ...data, _updatedAt: Date.now() });
return true;
} catch (error) {
console.error(`❌ dbUpdate error at ${path}:`, error.message);
return false;
}
}
/**
* Push to a list (auto-ID)
*/
async function dbPush(path, data) {
try {
const ref = db.ref(path).push();
await ref.set({ ...data, id: ref.key, _createdAt: Date.now() });
return ref.key;
} catch (error) {
console.error(`❌ dbPush error at ${path}:`, error.message);
return null;
}
}
/**
* Delete a path
*/
async function dbDelete(path) {
try {
await db.ref(path).remove();
return true;
} catch (error) {
console.error(`❌ dbDelete error at ${path}:`, error.message);
return false;
}
}
/**
* Query children where field == value
*/
async function dbQuery(path, orderBy, equalTo, limitToLast = null) {
try {
let ref = db.ref(path).orderByChild(orderBy).equalTo(equalTo);
if (limitToLast) ref = ref.limitToLast(limitToLast);
const snap = await ref.once('value');
if (!snap.exists()) return [];
const results = [];
snap.forEach(child => results.push({ _key: child.key, ...child.val() }));
return results;
} catch (error) {
console.error(`❌ dbQuery error at ${path}:`, error.message);
return [];
}
}
/**
* Get all children of a path
*/
async function dbGetAll(path) {
try {
const snap = await db.ref(path).once('value');
if (!snap.exists()) return [];
const results = [];
snap.forEach(child => results.push({ _key: child.key, ...child.val() }));
return results;
} catch (error) {
console.error(`❌ dbGetAll error at ${path}:`, error.message);
return [];
}
}
/**
* Listen to realtime updates at a path
*/
function dbListen(path, callback) {
const ref = db.ref(path);
ref.on('value', (snapshot) => {
callback(snapshot.exists() ? snapshot.val() : null);
});
return () => ref.off(); // Return unsubscribe function
}
module.exports = {
admin,
db,
auth,
messaging,
dbGet,
dbSet,
dbUpdate,
dbPush,
dbDelete,
dbQuery,
dbGetAll,
dbListen
};