Skip to content

Instantly share code, notes, and snippets.

@davidseek
Last active January 28, 2021 22:05
Show Gist options
  • Save davidseek/336b7813328aeb6c9a0c6f799a792c74 to your computer and use it in GitHub Desktop.
Save davidseek/336b7813328aeb6c9a0c6f799a792c74 to your computer and use it in GitHub Desktop.
Push Notificaiton setNotificationsTrigger
/**
* This function will be called every day at 8AM pacific time.
* Scheduled as CRON job in cloud scheduler.
*/
// This function create an https API that we can call using a GET request.
export const setNotificationsTrigger = functions.https.onRequest(async (_, response) => {
// We're using a try catch block to take advantage of the
// very nice `await` syntax, while also handling errors properly.
try {
// First we want to get our tasks.
// Await basically means, that we want to wait for the closure
// result of `getIncompleteTasks` before proceeding.
const tasks = await getIncompleteTasks()
// Then we use our formatter function to get a dictionary.
// [userID: [Task]]
const convertedTasks = getFormatted(tasks)
// Now we create an empty array of Promises.
// Look at it as an Array of closures.
// The Swift syntax could be something like:
// let promises = [(Any) -> Void]()
const promises: Promise<any>[] = []
// We want to iterate over our dictionary
for (let userID in convertedTasks) {
// To get each user's tasks
let userTasks = convertedTasks[userID]
// And if we have at least 1 open task...
if (userTasks.length > 0) {
// We need to add the functiont to notify a user
// to the Promises array.
// Note: We're not adding the result of the notification function,
// but the actual function.
// We want to add the function's callback to our Array of callbacks.
promises.push(notifyUser(userID, userTasks.length))
}
}
// Lastly we await for the execution and
// result of ALL functions at the same time
const result = await Promise.all(promises)
// Here we're just sending the response to close the network request.
response.send(result.filter((element: string) => {
// The filter now filters out all Promises that
// did not return a value for the result of the message.
// Remember, if the user.fcmToken was undefined,
// we did not send a notification, but returned undefined.
return typeof element !== 'undefined' && element !== null
}));
} catch (error) {
// Return the error if there was one.
response.send(error);
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment