Last active
February 15, 2018 23:55
-
-
Save yonahforst/0ce22010ddf6350af9eb548612410c7b to your computer and use it in GitHub Desktop.
index.js
This file contains 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
const functions = require('firebase-functions') | |
const admin = require('firebase-admin') | |
const fetch = require('node-fetch') | |
admin.initializeApp(functions.config().firebase) | |
// create an authentication endpoint. | |
// calls our backend to validate JWT | |
// if it passes, generate firebase token for the user | |
module.exports.authenticate = functions.https | |
.onRequest((req, res) => { | |
const { method, query } = req | |
if (method !== 'GET') | |
return res.status(405).end() | |
return makeRequest('/authorize', query) | |
.then(uid => admin.auth().createCustomToken(uid)) | |
.then(token => res.status(200).send({ token })) | |
}) | |
// listen for new messages and notify our backend | |
module.exports.onNewMessage = functions.database | |
.ref(`messages/{roomId}/{messageId}`) | |
.onWrite(({ data, params }) => { | |
const { roomId, messageId } = params | |
const payload = data.val() | |
return Promise.all([ | |
admin.database().ref('chats').child(roomId).set(payload), | |
makeRequest('/newMessage', payload), | |
]) | |
}) | |
const makeRequest = (path, body) => { | |
return fetch('https://api.mybackend.com' + path, { | |
method: 'POST', | |
body: JSON.stringify(body), | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment