import Inject, { RegisterSingleton, ServiceProvider } from "@entity-access/entity-access/dist/di/di.js"; import BasePushService, { IPushPayload, IPushToken } from "../BasePushService.js"; import { initializeApp, cert } from 'firebase-admin/app'; import DBConfig from "../../DBConfig.js"; import { getMessaging, Message, Messaging } from "firebase-admin/messaging"; import ForwardPushService from "../forward/ForwardPushService.js"; import PushConfig from "../PushConfig.js"; @RegisterSingleton export default class FcmPushService extends BasePushService { config: PushConfig; client: Messaging; @Inject forward: ForwardPushService; protected async initConfig() { using scope = ServiceProvider.createScope(this); const db = scope.resolve(DBConfig); this.config = (await db.getOrCreate(PushConfig, {})).value as PushConfig; if (this.config.fcm?.serviceAccountJson) { const app = initializeApp({ credential: cert(this.config.fcm.serviceAccountJson) }); this.client = getMessaging(app); } } protected async pushMessage(token: IPushToken, payload: IPushPayload) { if (!this.client) { return this.forward.push(token, payload); } const { body , title } = payload; const msg = { token: token.deviceToken, notification: { body, title } } as Message; await this.client.send(msg); } }