order
This commit is contained in:
47
src/lib/firebase.ts
Normal file
47
src/lib/firebase.ts
Normal file
@@ -0,0 +1,47 @@
|
||||
import { initializeApp, getApps, type FirebaseApp } from "firebase/app";
|
||||
import { getMessaging, isSupported, type Messaging } from "firebase/messaging";
|
||||
|
||||
// این مقادیر عمومی و امن برای مرورگرند (بر خلاف کلید سرویساکانت بکاند که فقط
|
||||
// سمت سرور استفاده میشه) — از NEXT_PUBLIC_FIREBASE_* در .env.local میان
|
||||
const firebaseConfig = {
|
||||
apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
|
||||
authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
|
||||
projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
|
||||
storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,
|
||||
messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID,
|
||||
appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID,
|
||||
};
|
||||
|
||||
let app: FirebaseApp | null = null;
|
||||
|
||||
function getFirebaseApp(): FirebaseApp | null {
|
||||
if (typeof window === "undefined") return null;
|
||||
if (!firebaseConfig.apiKey) return null;
|
||||
if (!app) {
|
||||
app = getApps().length ? getApps()[0] : initializeApp(firebaseConfig);
|
||||
}
|
||||
return app;
|
||||
}
|
||||
|
||||
let messagingPromise: Promise<Messaging | null> | null = null;
|
||||
|
||||
/** Messaging فقط توی مرورگرهایی که Service Worker/Push API دارن پشتیبانی میشه
|
||||
* (سافاری قدیمی، حالت خصوصیِ بعضی مرورگرها و... نه) — isSupported این رو چک میکنه */
|
||||
export function getFirebaseMessaging(): Promise<Messaging | null> {
|
||||
if (!messagingPromise) {
|
||||
messagingPromise = (async () => {
|
||||
const fbApp = getFirebaseApp();
|
||||
if (!fbApp) return null;
|
||||
try {
|
||||
const supported = await isSupported();
|
||||
if (!supported) return null;
|
||||
return getMessaging(fbApp);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
})();
|
||||
}
|
||||
return messagingPromise;
|
||||
}
|
||||
|
||||
export { firebaseConfig };
|
||||
Reference in New Issue
Block a user