Skip to content

Commit

Permalink
fix: initialize firebase admin app only if required
Browse files Browse the repository at this point in the history
  • Loading branch information
invertedEcho committed Dec 21, 2024
1 parent 6439bc4 commit bffa54b
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 19 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,6 @@ jobs:

- name: Run tests
run: |
echo DATABASE_URL=${{ secrets.DATABASE_URL }} >> .env.test
echo DATABASE_URL=${{ secrets.DATABASE_URL }} >> .env.test && echo FIREBASE_SERVICE_ACCOUNT_JSON_CONTENT=${{ secrets.FIREBASE_SERVICE_ACCOUNT_JSON_CONTENT }} >> .env.test
pnpm test
working-directory: ./backend
18 changes: 0 additions & 18 deletions backend/src/main.ts
Original file line number Diff line number Diff line change
@@ -1,30 +1,12 @@
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

import firebaseAdmin from 'firebase-admin';

async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.setGlobalPrefix('api');
app.enableCors();
await app.listen(3000, '0.0.0.0');

const firebaseServiceAccountJsonContent =
process.env.FIREBASE_SERVICE_ACCOUNT_JSON_CONTENT;

// TODO: should probably do the same for all other environment variables too.
if (firebaseServiceAccountJsonContent === undefined) {
throw new Error(
'FIREBASE_SERVICE_ACCOUNT_JSON_CONTENT environment variable must be set.',
);
}

firebaseAdmin.initializeApp({
credential: firebaseAdmin.credential.cert(
JSON.parse(firebaseServiceAccountJsonContent),
),
});

const appUrl = await app.getUrl();
console.log(`Flatshare Backend is running on: ${appUrl}`);
}
Expand Down
23 changes: 23 additions & 0 deletions backend/src/notifications/notification.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,33 @@
import { Message, getMessaging } from 'firebase-admin/messaging';
import firebaseAdmin from 'firebase-admin';

if (firebaseAdmin.apps.length === 0) {
const firebaseServiceAccountJsonContent =
process.env.FIREBASE_SERVICE_ACCOUNT_JSON_CONTENT;

// TODO: should probably do the same for all other environment variables too.
if (firebaseServiceAccountJsonContent === undefined) {
throw new Error(
'FIREBASE_SERVICE_ACCOUNT_JSON_CONTENT environment variable must be set.',
);
}

firebaseAdmin.initializeApp({
credential: firebaseAdmin.credential.cert(
JSON.parse(firebaseServiceAccountJsonContent),
),
});
}

export async function sendFirebaseMessages({
messages,
}: {
messages: Message[];
}) {
if (messages.length === 0) {
return;
}

const messaging = getMessaging();
const response = await messaging.sendEach(messages);
if (response.failureCount > 0) {
Expand Down

0 comments on commit bffa54b

Please sign in to comment.