Last active
January 1, 2019 19:58
-
-
Save hiranya911/611800523fef373ff7e808fb0f54e1ea to your computer and use it in GitHub Desktop.
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
import * as functions from 'firebase-functions'; | |
import * as admin from 'firebase-admin'; | |
admin.initializeApp(); | |
const firestore = admin.firestore(); | |
export const sendCryptoAlerts = functions.firestore.document('prices/{currency}') | |
.onUpdate(async (change, context) => { | |
const currencyId: string = context.params.currency; | |
const data = change.after.data(); | |
const newPrice: number = data.value; | |
console.log(`Price of ${currencyId} changed to USD ${newPrice}`); | |
const tokens = await findTargetDevices(currencyId, newPrice); | |
console.log(`Notifying ${tokens.length} devices`); | |
const promises: Array<Promise<string>> = []; | |
tokens.forEach((token) => { | |
const result = admin.messaging().send({ | |
token, | |
notification: { | |
title: 'Crypto Price Alert', | |
body: `${data.name} price changed to USD ${newPrice}.`, | |
}, | |
}); | |
promises.push(result); | |
}); | |
return await Promise.all(promises); | |
}); | |
async function findTargetDevices(currencyId: string, price: number): Promise<string[]> { | |
const prefs = firestore.collection('prefs'); | |
const minQuery = prefs.where(`${currencyId}_min`, '>', price).get(); | |
const maxQuery = prefs.where(`${currencyId}_max`, '<', price).get(); | |
const tokens: string[] = []; | |
(await minQuery).forEach((doc) => { | |
tokens.push(doc.data().token); | |
}); | |
(await maxQuery).forEach((doc) => { | |
tokens.push(doc.data().token); | |
}); | |
return tokens; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment