FCM test
This commit is contained in:
@@ -112,4 +112,47 @@ router.post('/unsubscribe', authMiddleware, async (req, res) => {
|
||||
} catch (e) { res.status(500).json({ error: e.message }); }
|
||||
});
|
||||
|
||||
// Send a test push to the requesting user's own device — for diagnosing FCM setup
|
||||
router.post('/test', authMiddleware, async (req, res) => {
|
||||
try {
|
||||
const subs = await query(req.schema,
|
||||
'SELECT * FROM push_subscriptions WHERE user_id = $1 AND fcm_token IS NOT NULL',
|
||||
[req.user.id]
|
||||
);
|
||||
if (subs.length === 0) {
|
||||
return res.status(404).json({
|
||||
error: 'No push subscription found for your account. Grant notification permission and reload the app first.',
|
||||
});
|
||||
}
|
||||
|
||||
const messaging = getMessaging();
|
||||
if (!messaging) {
|
||||
return res.status(503).json({ error: 'Firebase Admin not initialised on server — check FIREBASE_SERVICE_ACCOUNT in .env' });
|
||||
}
|
||||
|
||||
const results = [];
|
||||
for (const sub of subs) {
|
||||
try {
|
||||
await messaging.send({
|
||||
token: sub.fcm_token,
|
||||
data: {
|
||||
title: 'RosterChirp Test',
|
||||
body: 'Push notifications are working! 🎉',
|
||||
url: '/',
|
||||
groupId: '',
|
||||
},
|
||||
android: { priority: 'high' },
|
||||
webpush: { headers: { Urgency: 'high' } },
|
||||
});
|
||||
results.push({ device: sub.device, status: 'sent' });
|
||||
console.log(`[Push] Test notification sent to user ${req.user.id} device=${sub.device}`);
|
||||
} catch (err) {
|
||||
results.push({ device: sub.device, status: 'failed', error: err.message, code: err.code });
|
||||
console.error(`[Push] Test notification failed for user ${req.user.id} device=${sub.device}:`, err.message);
|
||||
}
|
||||
}
|
||||
res.json({ results });
|
||||
} catch (e) { res.status(500).json({ error: e.message }); }
|
||||
});
|
||||
|
||||
module.exports = { router, sendPushToUser };
|
||||
|
||||
Reference in New Issue
Block a user