FirebaseClient.js 2.03 KB
Newer Older
renato's avatar
renato committed
1 2 3 4 5 6
import FirebaseConstants from "./FirebaseConstants";

const API_URL = "https://fcm.googleapis.com/fcm/send";

class FirebaseClient {

7 8 9
  constructor() {
    this.sendData = this.sendData.bind(this);
    this.sendNotification = this.sendNotification.bind(this);
renato's avatar
renato committed
10
    this.sendNotificationWithData = this.sendNotificationWithData.bind(this);
11 12 13
  }

  sendNotification(token) {
renato's avatar
renato committed
14
    let body = {
15
    	"to": token,
renato's avatar
renato committed
16 17 18
      "notification":{
    		"title": "Simple FCM Client",
    		"body": "This is a notification with only NOTIFICATION.",
renato's avatar
renato committed
19 20 21 22 23 24 25 26 27
    		"sound": "default",
    		"click_action": "fcm.ACTION.HELLO"
    	},
    	"priority": 10
    }

    this._send(JSON.stringify(body), "notification");
  }

28
  sendData(token) {
renato's avatar
renato committed
29
    let body = {
30
    	"to": token,
renato's avatar
renato committed
31
      "data":{
renato's avatar
renato committed
32 33
    		"title": "Simple FCM Client",
    		"body": "This is a notification with only DATA.",
renato's avatar
renato committed
34
    		"sound": "default",
renato's avatar
renato committed
35 36
    		"click_action": "fcm.ACTION.HELLO",
    		"remote": true
renato's avatar
renato committed
37
    	},
renato's avatar
renato committed
38
    	"priority": "normal"
renato's avatar
renato committed
39 40 41 42 43
    }

    this._send(JSON.stringify(body), "data");
  }

renato's avatar
renato committed
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
  sendNotificationWithData(token) {
    let body = {
      "to": token,
      "notification":{
    		"title": "Simple FCM Client",
    		"body": "This is a notification with NOTIFICATION and DATA (NOTIF).",
    		"sound": "default",
    		"click_action": "fcm.ACTION.HELLO"
    	},
    	"data":{
    		"title": "Simple FCM Client",
    		"body": "This is a notification with NOTIFICATION and DATA (DATA)",
    		"click_action": "fcm.ACTION.HELLO",
    		"remote": true
    	},
    	"priority": "high"
    }

    this._send(JSON.stringify(body), "notification-data");
  }

renato's avatar
renato committed
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
  _send(body, type) {
  	let headers = new Headers({
  		"Content-Type": "application/json",
  		"Content-Length": parseInt(body.length),
      "Authorization": "key=" + FirebaseConstants.KEY
  	});

  	fetch(API_URL, { method: "POST", headers, body })
  		.then(response => console.log("Send " + type + " response", response))
  		.catch(error => console.log("Error sending " + type, error));
  }

}

let firebaseClient = new FirebaseClient();
export default firebaseClient;