Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

notificationPermissions.ts

67 lines1.9 KB

1import * as Notifications from "expo-notifications";
2import * as Effect from "effect/Effect";
3import * as Schema from "effect/Schema";
4import { Platform } from "react-native";
5​
6export type NotificationPermissionResult =
7 | { readonly type: "unsupported" }
8 | { readonly type: "granted" }
9 | { readonly type: "denied"; readonly canAskAgain: boolean };
10​
11export class NotificationPermissionReadError extends Schema.TaggedErrorClass<NotificationPermissionReadError>()(
12 "NotificationPermissionReadError",
13 {
14 cause: Schema.Defect(),
15 },
16) {
17 override get message(): string {
18 return "Failed to read notification permissions on iOS.";
19 }
21​
22export class NotificationPermissionRequestError extends Schema.TaggedErrorClass<NotificationPermissionRequestError>()(
23 "NotificationPermissionRequestError",
24 {
25 cause: Schema.Defect(),
26 },
27) {
28 override get message(): string {
29 return "Failed to request notification permissions on iOS.";
30 }
32​
33export const requestAgentNotificationPermission: Effect.Effect<
34 NotificationPermissionResult,
35 NotificationPermissionReadError | NotificationPermissionRequestError
36> = Effect.gen(function* () {
37 if (Platform.OS !== "ios") {
38 return { type: "unsupported" };
39 }
40​
41 const existing = yield* Effect.tryPromise({
42 try: () => Notifications.getPermissionsAsync(),
43 catch: (cause) => new NotificationPermissionReadError({ cause }),
44 });
45 if (existing.granted) {
46 return { type: "granted" };
47 }
48​
49 if (!existing.canAskAgain) {
50 return { type: "denied", canAskAgain: false };
51 }
52​
53 const requested = yield* Effect.tryPromise({
54 try: () =>
55 Notifications.requestPermissionsAsync({
56 ios: {
57 allowAlert: true,
58 allowBadge: true,
59 allowSound: true,
60 },
61 }),
62 catch: (cause) => new NotificationPermissionRequestError({ cause }),
63 });
64 return requested.granted
65 ? { type: "granted" }
66 : { type: "denied", canAskAgain: requested.canAskAgain };
67});