Skip to content

Instantly share code, notes, and snippets.

@yonahforst
Last active February 15, 2018 23:55
Show Gist options
  • Save yonahforst/0ce22010ddf6350af9eb548612410c7b to your computer and use it in GitHub Desktop.
Save yonahforst/0ce22010ddf6350af9eb548612410c7b to your computer and use it in GitHub Desktop.
index.js
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