stadtwerke/innungsapp/apps/mobile/lib/notifications.ts

46 lines
1.3 KiB
TypeScript

import * as Notifications from 'expo-notifications'
import { Platform } from 'react-native'
import { trpc } from './trpc'
import { queryClient } from './trpc'
Notifications.setNotificationHandler({
handleNotification: async () => ({
shouldShowAlert: true,
shouldPlaySound: true,
shouldSetBadge: true,
shouldShowBanner: true,
shouldShowList: true,
}),
})
export async function setupPushNotifications() {
if (Platform.OS === 'web') return
const { status: existingStatus } = await Notifications.getPermissionsAsync()
let finalStatus = existingStatus
if (existingStatus !== 'granted') {
const { status } = await Notifications.requestPermissionsAsync()
finalStatus = status
}
if (finalStatus !== 'granted') return
const token = await Notifications.getExpoPushTokenAsync({
projectId: process.env.EXPO_PUBLIC_PROJECT_ID,
})
// Store push token on the server
// We call the tRPC mutation to save the token
const caller = trpc.createClient as never
// Simple fetch to avoid circular deps:
const apiUrl = process.env.EXPO_PUBLIC_API_URL ?? 'http://localhost:3000'
await fetch(`${apiUrl}/api/push-token`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ token: token.data }),
}).catch(() => {
// Silently fail — push is optional
})
}