import { urlB64ToUint8Array } from './utils' ; export async function notify ( ) { const perm = await requestPerm ( ) ; console . log ( 'web push sub' , perm ) ; return perm ; } function getServerKey ( ) { return fetch ( 'https://ionic-beer-push-server.herokuapp.com/publickey' ) . then ( ( res ) => { return res . json ( ) ; } ) ; } function requestPerm ( ) { navigator . serviceWorker . getRegistration ( ) . then ( ( reg ) => { reg . pushManager . getSubscription ( ) . then ( ( sub ) => { if ( sub === null ) { getServerKey ( ) . then ( ( data ) => { console . log ( data ) ; const serverKey = urlB64ToUint8Array ( data ) ; console . log ( serverKey ) ; return reg . pushManager . subscribe ( { userVisibleOnly : true , applicationServerKey : serverKey } ) . then ( ( sub ) => { console . log ( 'web push subscription: ' , sub ) ; sendTokenToServer ( sub ) ; } ) ; } ) ; } } ) ; } ) ; } function sendTokenToServer ( token ) { console . log ( token ) ; fetch ( 'https://ionic-beer-push-server.herokuapp.com/notifysub' , { method : 'POST' , body : JSON . stringify ( { sub : token } ) , headers : { 'Accept' : 'application/json' , 'Content-Type' : 'application/json' } } ) . then ( ( res ) => { return res . json ( ) ; } ) . then ( ( data ) => { console . log ( data ) ; } ) ; }