Untitled

mail@pastecode.io avatar
unknown
plain_text
8 months ago
1.8 kB
1
Indexable
Never
export const getToken2 = async (setTokenFound, save) => {
  const getTok = async (setTokenFound, retry) => {
    try {
      if (retry) {
        console.log('tilraun 2');
      } else {
        console.log('tilraun 1');
      };
      const currentToken = await getToken(messaging, {vapidKey: process.env.REACT_APP_FIREBASE_VAPID_KEY});
      if (currentToken) {
        console.info('current token for client: ', currentToken);
        const deviceToken = {
          token: currentToken,
          timestamp: serverTimestamp(),
        };
        if (save) {
          mergeArraysInFirebase(currentToken);
        }
        setTokenFound(1);
        return 1;
      } else {
        setTokenFound(0);
        return 0;
      }
    } catch (err) {
      console.log('HÆ');
      console.log(err);
      console.log('BÆ');
      if (!retry) {
        console.log('retry');
        await new Promise((resolve) => setTimeout(resolve, 1000));
        console.log('bíð í eina sek');
        return getTok(setTokenFound, true);
      } else {
        console.log('ekki retry');
        const deviceToken = {
          lastErr: err.toString(),
          timestamp: serverTimestamp(),
        };
        await setDoc(doc(db, 'messagingTokens', auth.currentUser.email), deviceToken, {merge: true});
        setTokenFound(-1);
        return -1;
      }
    }
  };
  if ('serviceWorker' in navigator) {
    try {
      const swReg2 = await navigator.serviceWorker.register('../firebase-messaging-sw.js');
      console.log('Firebase Worker is registered', swReg2);
      const ret = await getTok(setTokenFound);
      return ret;
    } catch (error) {
      console.error('Service Worker registration failed:', error);
    }
  }
};
Leave a Comment