0

I have this code but I need to translate it to Typescript, and having issues finding the request module

function sendNotificationToUser(username, message, onSuccess) {
request({
  url: 'https://fcm.googleapis.com/fcm/send',
  method: 'POST',
  headers: {
    'Content-Type' :' application/json',
    'Authorization': 'key='+API_KEY
  },
  body: JSON.stringify({
    notification: {
      title: message
    },
    to : '/topics/user_'+username
  })
}, function(error, response, body) {
  if (error) { console.error(error); }
  else if (response.statusCode >= 400) { 
    console.error('HTTP Error: '+response.statusCode+' - '+response.statusMessage); 
  }
  else {
    onSuccess();
  }
});

}

SHAI
  • 789
  • 3
  • 10
  • 43

1 Answers1

2
    const response = await fetch("https://fcm.googleapis.com/fcm/send", {
      method: 'POST',
      body: JSON.stringify({notification: {title: message},to : '/topics/user_'+username}),
      headers: {'Content-Type': 'application/json', 'Authorization': 'key='+API_KEY} 
    });
    
    if (!response.ok) 
    { 
        console.error("Error");
    }
    else if (response.statusCode >= 400) {
        console.error('HTTP Error: '+response.statusCode+' - '+response.statusMessage);
    }
    else{
        onSuccess();
    }
Blazkowicz
  • 180
  • 9
  • Thanks! Trying to work on it as I get this message from my server "ReferenceError: fetch is not defined at sendNotificationToUser . Trying to understand why it doesn't work – SHAI Mar 12 '21 at 23:10
  • 1
    Try looking at this link. https://stackoverflow.com/a/48433898/6110031 – Blazkowicz Mar 12 '21 at 23:27
  • Thank you it worked! Not sure why someone tried to vote you down... I had to install the fetch module – SHAI Mar 13 '21 at 18:08