Skip to content

Instantly share code, notes, and snippets.

@n1lesh
Last active May 31, 2023 12:24
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save n1lesh/3f06f85f47d546df2c21020a9b77c7b4 to your computer and use it in GitHub Desktop.
Save n1lesh/3f06f85f47d546df2c21020a9b77c7b4 to your computer and use it in GitHub Desktop.
Firebase Cloud Messaging with Node.js
'use strict'
const app = require('express')(),
request = require('request'),
mongo = require('mongodb'),
bodyParser = require('body-parser')
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
extended: false
}))
const MongoClient = mongo.MongoClient
const url = 'mongodb://localhost:27017/myDatabase'
app.get('/notifications', (req, res) => {
res.sendFile(__dirname + '/notifcenter.html')
})
app.post('/store', (req, res) => {
MongoClient.connect(url, (err, db) => {
if (err) throw err
else {
db.collection('tokens').insertOne(req.body, (err, body) => {
if (err) throw err
res.sendStatus(200)
})
}
db.close()
})
})
const sendNotifications = (data) => {
const dataString = JSON.stringify(data)
const headers = {
'Authorization': 'key=<your firebase legacy server key>',
'Content-Type': 'application/json',
'Content-Length': dataString.length
}
const options = {
uri: 'https://fcm.googleapis.com/fcm/send',
method: 'POST',
headers: headers,
json: data
}
request(options, function (err, res, body) {
if (err) throw err
else console.log(body)
})
}
const sendToTopics = (msg, title, topic, response) => {
const data = {
"data": {
"body": msg,
"title": title
}
}
data['to'] = '/topics/' + topic
sendNotifications(data)
response.sendStatus(200)
}
const sendToAll = (msg, title, regIdArray, response) => {
const data = {
"data": {
"body": msg,
"title": title
}
}
const folds = regIdArray.length % 1000
for (let i = 0; i < folds; i++) {
let start = i * 1000,
end = (i + 1) * 1000
data['registration_ids'] = regIdArray.slice(start, end).map((item) => {
return item['token']
})
sendNotifications(data)
}
response.sendStatus(200)
}
app.post('/notify', (req, res) => {
let msg = req.body.message,
title = req.body.title,
type = req.body.type,
topic = req.body.topic
if (type === 'topic') {
sendToTopics(msg, title, topic, res)
} else {
MongoClient.connect(url, function (err, db) {
if (err) throw err
else {
db.collection('tokens').find({}).toArray((err, docs) => {
sendToAll(msg, title, docs, res)
})
}
db.close()
})
}
})
app.listen(8000)
<!DOCTYPE html>
<html>
<head>
<title>Notification Center</title>
<style>
body {
text-align: center;
}
h1 {
font-size: 40px;
font-family: Verdana, Geneva, Tahoma, sans-serif;
color: #444;
}
input[type=text] {
width: 300px;
margin: 0 auto;
display: block;
}
.border {
padding: 15px;
border-color: #7a7a7a;
border-style: solid;
font-family: Verdana, Geneva, Tahoma, sans-serif;
border-width: 2px;
border-radius: 3px;
}
textarea {
width: 300px;
margin: 0 auto;
height: 200px;
display: block;
margin-top: 20px;
}
button {
background: #444;
margin-top: 20px;
color: white;
display: block;
margin: 20px auto;
}
input[type=radio] {
margin: 20px 10px;
}
select {
display: block;
width: 200px;
display: none;
margin: 10px auto;
}
</style>
</head>
<body>
<h1>Notification Center</h1>
<form method="post" action="http://localhost:8000/notify">
<input class="border" type="text" name="title" placeholder="notiification title">
<textarea class="border" name="message" placeholder="message"></textarea>
<input type="radio" name="type" value="all">Send to all
<input type="radio" name="type" value="topic">Send to topic subscribers only
<select class="border" name="topic">
<option value="topic1">Topic 1</option>
<option value="topic2">Topic 2</option>
<option value="topic3">Topic 3</option>
</select>
<button class="border">Send Notification</button>
</form>
<script>
var all = document.getElementsByName('type')[0]
var topic = document.getElementsByName('type')[1]
var select = document.getElementsByTagName('select')[0]
console.log(all, topic, select)
topic.onclick = function () {
select.style.display = 'block'
all.checked = false
}
all.onclick = function () {
select.style.display = 'none'
topic.checked = false
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment