Created
June 5, 2017 19:56
-
-
Save elon-gs/b91d17c64636daeacb237707b5df9da2 to your computer and use it in GitHub Desktop.
Simple Firebase trigger Function to send a Twilio SMS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// index.js for Firebase Functions | |
// SMS is triggered when an alert object is added to the alert queue path | |
const functions = require('firebase-functions'); | |
const admin = require('firebase-admin'); | |
const twilio = require('twilio'); | |
admin.initializeApp(functions.config().firebase); | |
const db = admin.database(); | |
const ALERT_QUEUE_PATH = '/alerts/queue'; // objects stored here trigger SMS | |
// Firebase trigger Function to send an SMS | |
exports.watchAlertQueue = functions.database.ref(`${ALERT_QUEUE_PATH}/{ALERT}`).onWrite( | |
(event) => new Promise((resolve, reject) => { | |
// on trigger, an event is passed in | |
// event.data.val() will be a single object, | |
// because we included a wildcard in the watched path, {ALERT} | |
// we return a Promise because this Function makes asynchronous calls | |
const alert = event.data.val(); | |
const message = alert.alertText; // text for SMS contained in alertText property | |
const client = new twilio.RestClient(accountSid, authToken); // TODO: Add values for your Twilio account | |
client.messages.create({ | |
to: MY_NUMBER, // TODO: add destination number | |
from: TWILIO_NUMBER, // TODO: add your Twilio outbound number | |
body: message, | |
}, (err) => { | |
if (err) { | |
// didn't go through, let's fulfill promise with a rejection | |
console.error(err.message); | |
return reject(); | |
} | |
// success -- let's record this, then remove the alert from the queue | |
const ALERT_RECORD_PATH = '/alerts/records'; | |
db.ref(`${ALERT_RECORD_PATH}/${alert.GUID}`).set(alert).then(() => { | |
db.ref(`${ALERT_QUEUE_PATH}/${alert.GUID}`).remove().then(() => | |
resolve()).catch(() => reject()); | |
}).catch(() => reject()); | |
}); | |
}) | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment