Last active
January 28, 2021 21:45
-
-
Save davidseek/5419082f2de80641272c17cd814f2303 to your computer and use it in GitHub Desktop.
Push Notification notifyUser
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
/** | |
* Function to send a Push Notification using Firebase Messaging. | |
* @param userID The user to receive the push message. | |
* @param taskCount The amount of open tasks. | |
* @returns Returns the message ID or undefined in case of failure. | |
*/ | |
function notifyUser(userID: string, taskCount: number): Promise<string | undefined> { | |
// Again we're just initiating a new Promise. | |
// A closure that can succeed and fail. | |
return new Promise(async (resolve, reject) => { | |
// This function just gets us the user based on the userID. | |
// There's no value in me providing this function. | |
// It's just getting the data associated with an ID from the database. | |
const user = await getUser(userID) | |
// Next we need to check, if the user exists | |
// AND -> If they registered for push notifications, or not. | |
// The `gcmToken` is what we sent from the mobile application to the server | |
if (!user || !user.gcmToken) { | |
// If we end up here, then we want to pass undefined | |
// (aka nil) to the closure that expects a message ID | |
resolve(undefined) | |
return | |
} | |
// The following is the actual payload. | |
// Most of it is boilerplate code. | |
// Check out firebase.messaging.Message for more. | |
// https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages | |
// | |
// `titleLocKey`, `locKey` and `locArgs` are the only relevant fields for us. | |
// `token` defines who the receiver of the Notification will be. | |
const payload = { | |
apns: { | |
payload: { | |
aps: { | |
alert: { | |
titleLocKey: "OPEN_TASKS_HEADER", | |
locKey: "OPEN_TASKS_BODY", | |
locArgs: [ | |
`${taskCount}` | |
] | |
}, | |
"mutable-content": false, | |
"thread-id": "open-tasks", | |
badge: taskCount | |
}, | |
} | |
}, | |
token: user.gcmToken | |
} | |
// The rest is just boilerplate. | |
// Using Firebase's messaging object, to send the payload. | |
messaging.send(payload) | |
.then((response: string) => { | |
// Handle this however you see fit. | |
// The message was sent successfully. | |
resolve(`Did send message to: ${userID} about ${taskCount} task/s ID: ${response}`) | |
}) | |
.catch((error: Error) => { | |
// The message was not sent. | |
// You need to check the error and debug why. | |
reject(error) | |
}); | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment