/
createNotificationService.native.ts
60 lines (53 loc) · 1.79 KB
/
createNotificationService.native.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import type RNFBMessaging from '@react-native-firebase/messaging';
import { Platform } from 'react-native';
import type * as Permissions from 'react-native-permissions';
import type { NotificationServiceInterface } from './types';
const createNativeNotificationService = ({
messagingModule,
permissionModule,
}: {
messagingModule: typeof RNFBMessaging;
permissionModule: typeof Permissions;
}): NotificationServiceInterface => {
const module = messagingModule();
const authorizedStatus = [
messagingModule.AuthorizationStatus.AUTHORIZED,
messagingModule.AuthorizationStatus.PROVISIONAL,
];
return {
getAPNSToken(): Promise<string | null> {
return module.getAPNSToken();
},
getFCMToken(): Promise<string | null> {
return module.getToken();
},
async hasPushPermission(): Promise<boolean> {
if (Platform.OS === 'android') {
const result = await permissionModule.checkNotifications();
return result.status === 'granted';
}
if (Platform.OS === 'ios') {
const status = await module.hasPermission();
return authorizedStatus.includes(status);
}
return false;
},
async requestPushPermission(): Promise<boolean> {
if (Platform.OS === 'android') {
const result = await permissionModule.requestNotifications([]);
return result.status === 'granted';
}
if (Platform.OS === 'ios') {
const status = await module.requestPermission();
return authorizedStatus.includes(status);
}
return false;
},
onTokenRefresh(handler: (token: string) => void): () => void | undefined {
return module.onTokenRefresh((token) => {
if (Platform.OS === 'android') handler(token);
});
},
};
};
export default createNativeNotificationService;