Skip to content

Instantly share code, notes, and snippets.

@erickvieira
Created May 31, 2020 13:37
Show Gist options
  • Save erickvieira/8da33fe6cfe54bd95393fb0d6009a52b to your computer and use it in GitHub Desktop.
Save erickvieira/8da33fe6cfe54bd95393fb0d6009a52b to your computer and use it in GitHub Desktop.
import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
import * as express from 'express';
import * as bodyParser from 'body-parser';
import * as cors from 'cors';
/**
* Apenas uma imagem de demonstração
*/
const appIcon = "https://img.icons8.com/carbon-copy/2x/bot.png";
/**
* É necessário criar um app express convencional para suportar requisições
* http do app
*/
const app = express();
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.options('*', cors());
app.get('/subscribe', async (req, res) => {
const data = req.body;
try {
await admin.messaging().subscribeToTopic(data.token, data.topic);
res.status(200).send({
subscribed: true,
message: `inscrito no topico ${data.topic}`
})
}
catch (err) {
res.status(500).send({
err
})
}
});
app.get('/unsubscribe', async (req, res) => {
const data = req.body;
try {
await admin.messaging().unsubscribeFromTopic(data.token, data.topic);
res.status(200).send({
subscribed: false,
message: `desinscrito no topico ${data.topic}`
})
}
catch (err) {
res.status(500).send({
err
})
}
});
exports.topicHttp = functions.https.onRequest(app);
// =============================================================================
/**
* Implementação necessária para observar as mudanças na collection
* chamada "webpush"
*/
admin.initializeApp(functions.config().firebase);
exports.getCurrentVersion = functions.https.onCall(() => {
return '0.0.1';
})
exports.subscribeToTopic = functions.https.onCall(async (data, _) => {
await admin.messaging().subscribeToTopic(data.token, data.topic);
return `inscrito no topico ${data.topic}`;
});
exports.unsubscribeFromTopic = functions.https.onCall(async (data, _) => {
await admin.messaging().unsubscribeFromTopic(data.token, data.topic);
return `desinscrito do topico ${data.topic}`;
});
/**
*
*/
exports.sendOnFirestoreCreate = functions.firestore.document(
'webpush/{pushId}'
).onCreate(async (snapshot, _) => {
const { title = "", body = "", topic = "elevenstars", image = "" } = snapshot.data();
const payload: admin.messaging.Message = {
android: {
collapseKey: 'Eleven Stars',
priority: 'high',
ttl: 3,
restrictedPackageName: 'app.elevenstars.com',
notification: {
color: '#ff6600',
title: title,
body: body,
tag: 'Eleven Stars',
icon: appIcon
}
},
webpush: {
notification: {
title: title,
body: body,
vibrate: [200, 100, 200],
tag: 'Eleven Stars',
image: image,
badge: appIcon,
icon: appIcon
},
fcmOptions: {
link: 'https://app.elevenstars.com'
}
},
topic: topic || 'elevenstars'
};
/**
* Descomente as linhas a seguir para verificar se as push notifications
* estão sendo disparadas com o valor correto
*/
// const ref = admin.database().ref('webPushLog');
// await ref.push({ title, body, topic, image });
return admin.messaging().send(payload);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment