77 lines
2.2 KiB
JavaScript
77 lines
2.2 KiB
JavaScript
const DEFAULT_FCM_TOPIC = 'route_alerts';
|
|
const DEFAULT_FCM_ANDROID_CHANNEL_ID = 'route_alerts';
|
|
|
|
function parseBoolean(value, fallback = false) {
|
|
if (value === undefined || value === null || String(value).trim() === '') {
|
|
return fallback;
|
|
}
|
|
|
|
return ['1', 'true', 'yes', 'on'].includes(String(value).trim().toLowerCase());
|
|
}
|
|
|
|
function getFirebaseConfig(env = process.env) {
|
|
const topic = String(env.FCM_TOPIC || '').trim();
|
|
const androidChannelId = String(env.FCM_ANDROID_CHANNEL_ID || '').trim();
|
|
const projectId = String(env.FIREBASE_PROJECT_ID || '').trim();
|
|
|
|
return {
|
|
enabled: parseBoolean(env.FCM_ENABLED, false),
|
|
topic: topic || DEFAULT_FCM_TOPIC,
|
|
androidChannelId: androidChannelId || DEFAULT_FCM_ANDROID_CHANNEL_ID,
|
|
projectId: projectId || undefined
|
|
};
|
|
}
|
|
|
|
let messagingSingleton;
|
|
|
|
function getFirebaseApp(config = getFirebaseConfig()) {
|
|
// Keep Firebase Admin lazy: deployments that do not receive passenger telemetry
|
|
// still run without local ADC credentials.
|
|
const { applicationDefault, getApps, initializeApp } = require('firebase-admin/app');
|
|
|
|
const existingApp = getApps()[0];
|
|
return existingApp || initializeApp({
|
|
credential: applicationDefault(),
|
|
...(config.projectId ? { projectId: config.projectId } : {})
|
|
});
|
|
}
|
|
|
|
function createFirebaseMessaging(config = getFirebaseConfig()) {
|
|
if (!config.enabled) {
|
|
return null;
|
|
}
|
|
|
|
// Keep Firebase optional for disabled/local environments. These modular
|
|
// imports are evaluated only when an enabled notification is actually sent.
|
|
const { getMessaging } = require('firebase-admin/messaging');
|
|
return getMessaging(getFirebaseApp(config));
|
|
}
|
|
|
|
function getFirebaseMessaging(config = getFirebaseConfig()) {
|
|
if (!config.enabled) {
|
|
return null;
|
|
}
|
|
|
|
if (!messagingSingleton) {
|
|
messagingSingleton = createFirebaseMessaging(config);
|
|
}
|
|
|
|
return messagingSingleton;
|
|
}
|
|
|
|
function createFirebaseAuth(config = getFirebaseConfig()) {
|
|
const { getAuth } = require('firebase-admin/auth');
|
|
return getAuth(getFirebaseApp(config));
|
|
}
|
|
|
|
module.exports = {
|
|
DEFAULT_FCM_TOPIC,
|
|
DEFAULT_FCM_ANDROID_CHANNEL_ID,
|
|
parseBoolean,
|
|
getFirebaseConfig,
|
|
getFirebaseApp,
|
|
createFirebaseAuth,
|
|
createFirebaseMessaging,
|
|
getFirebaseMessaging
|
|
};
|