Last active
July 2, 2018 11:02
-
-
Save mono0926/ddff8b45c539162c92d5fa4b8202a3d9 to your computer and use it in GitHub Desktop.
Firestoreにmessageが追加されたらプッシュ通知
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
export const onCharactersMessageCreate = functions.firestore.document(`/${User.entity}/{userId}/${Message.entity}/{messageId}`).onCreate(async event => { | |
const userId = event.params!.userId; | |
const userRef = firestore.collection(User.entity).doc(userId); | |
const tokenSnapshot = await userRef.collection(FcmToken.entity).get(); | |
const tokens = tokenSnapshot.docs.map(doc => { return doc.id; }); | |
const message = <Message> event.data.data(); | |
const title = (await new I18N('ja').notification())('newMessageTitle'); | |
const payload = notification.createPayload( | |
title, | |
message.text); | |
const response = await admin.messaging().sendToDevice(tokens, payload); | |
// 無効なtokenを削除 | |
const results = response.results.map((response, i) => { return { response, token: tokens[i] }; }); | |
const errorCodes = [ | |
'messaging/invalid-registration-token', | |
'messaging/registration-token-not-registered', | |
]; | |
for (const r of results) { | |
const error = r.response.error; | |
if (errorCodes.indexOf(error.code) > -1) { | |
console.info(`start deleteting: ${error.code}`); | |
await r.token.ref.delete(); | |
} else { | |
console.error(`unexpected error: ${error.code}`); | |
} | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment