1import { UnavailabilityError, Platform } from 'expo-modules-core';
2
3import PushTokenManager from './PushTokenManager';
4import { DevicePushToken } from './Tokens.types';
5
6let nativeTokenPromise: Promise<string> | null = null;
7
8export default async function getDevicePushTokenAsync(): Promise<DevicePushToken> {
9  if (!PushTokenManager.getDevicePushTokenAsync) {
10    throw new UnavailabilityError('ExpoNotifications', 'getDevicePushTokenAsync');
11  }
12
13  let devicePushToken: string | null = null;
14  if (nativeTokenPromise) {
15    // Reuse existing Promise
16    devicePushToken = await nativeTokenPromise;
17  } else {
18    // Create a new Promise and clear it afterwards
19    nativeTokenPromise = PushTokenManager.getDevicePushTokenAsync();
20    devicePushToken = await nativeTokenPromise;
21    nativeTokenPromise = null;
22  }
23
24  // @ts-ignore: TS thinks Platform.OS could be anything and can't decide what type is it
25  return { type: Platform.OS, data: devicePushToken };
26}
27