API notif dan penambahan package firebase-admin
Add: - src/app/api/mobile/notifications/ - src/lib/firebase-admin.ts ### No Issue
This commit is contained in:
44
src/app/api/mobile/notifications/route.ts
Normal file
44
src/app/api/mobile/notifications/route.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
// app/api/test/notifications/route.ts
|
||||
import { adminMessaging } from "@/lib/firebase-admin";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const { data } = await request.json();
|
||||
const { fcmToken, title, body: notificationBody } = data;
|
||||
|
||||
console.log("Data Notifikasi >>", data);
|
||||
|
||||
if (!fcmToken || !title) {
|
||||
return NextResponse.json(
|
||||
{ error: "Missing fcmToken or title" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const message = {
|
||||
token: fcmToken,
|
||||
notification: {
|
||||
title,
|
||||
body: notificationBody || "",
|
||||
},
|
||||
data: {
|
||||
sentAt: new Date().toISOString(), // ✅ Simpan metadata di data
|
||||
// contoh: senderId, type, etc.
|
||||
},
|
||||
};
|
||||
|
||||
console.log("[MSG]", message);
|
||||
|
||||
const response = await adminMessaging.send(message);
|
||||
console.log("✅ FCM sent:", response);
|
||||
|
||||
return NextResponse.json({ success: true, messageId: response });
|
||||
} catch (error: any) {
|
||||
console.error("❌ FCM error:", error);
|
||||
return NextResponse.json(
|
||||
{ error: error.message || "Failed to send FCM" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
24
src/lib/firebase-admin.ts
Normal file
24
src/lib/firebase-admin.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
// lib/firebase-admin.ts
|
||||
import { cert, getApp, getApps, initializeApp } from 'firebase-admin/app';
|
||||
import { getMessaging } from 'firebase-admin/messaging';
|
||||
|
||||
// Ambil dari environment
|
||||
const serviceAccount = {
|
||||
projectId: process.env.FIREBASE_ADMIN_PROJECT_ID,
|
||||
clientEmail: process.env.FIREBASE_ADMIN_CLIENT_EMAIL,
|
||||
privateKey: process.env.FIREBASE_ADMIN_PRIVATE_KEY?.replace(/\\n/g, '\n'),
|
||||
};
|
||||
|
||||
if (!serviceAccount.projectId || !serviceAccount.clientEmail || !serviceAccount.privateKey) {
|
||||
throw new Error('Firebase Admin credentials are missing in environment variables');
|
||||
}
|
||||
|
||||
// Inisialisasi hanya sekali
|
||||
const app = !getApps().length
|
||||
? initializeApp({
|
||||
credential: cert(serviceAccount),
|
||||
projectId: serviceAccount.projectId,
|
||||
})
|
||||
: getApp();
|
||||
|
||||
export const adminMessaging = getMessaging(app);
|
||||
Reference in New Issue
Block a user