Skip to content

Instantly share code, notes, and snippets.

@mono0926
Last active July 2, 2018 11:02
Show Gist options
  • Save mono0926/ddff8b45c539162c92d5fa4b8202a3d9 to your computer and use it in GitHub Desktop.
Save mono0926/ddff8b45c539162c92d5fa4b8202a3d9 to your computer and use it in GitHub Desktop.
Firestoreにmessageが追加されたらプッシュ通知
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