CWi*_*ley 6 async-await typescript google-cloud-functions firebase-cloud-messaging
我是Typescript的新手,我正在尝试使用async和await功能.我每隔一段时间就得到一些fcm网络超时,我相信这与正确回复我的承诺有关.
这是我发送推送通知的云功能.使用await关键字的两个函数是incrementBadgeCount,和sendPushNotification:
export const pushNotification = functions.firestore
.document('company/{companyId}/message/{messageId}/chat/{chatId}')
.onCreate(async event => {
const message = event.data.data();
const recipients = event.data.data().read;
const messageId = event.params.messageId;
const ids = [];
for (const key of Object.keys(recipients)) {
const val = recipients[key];
if (val === false) {
ids.push(key);
}
}
return await Promise.all(ids.map(async (id) => {
const memberPayload = await incrementBadgeCount(id);
const memberBadgeNumberString =
memberPayload.getBadgeCount().toString();
const senderName = message.sender.name;
const senderId = message.sender.id;
const senderMemberName = message.senderMember.name;
const toId = message.receiver.id;
const text = message.text;
const photoURL = message.photoURL;
const videoURL = message.videoURL;
const dealId = message.dealId;
const dealName = message.dealName;
const payload = {
notification: {
title: `${senderName}`,
click_action: 'exchange.booth.message',
sound: 'default',
badge: memberBadgeNumberString
},
data: { senderId, toId, messageId }
};
const options = {
contentAvailable: true
}
........
const deviceIDs = memberPayload.getDeviceID()
return await sendPushNotification(id, deviceIDs, payload, options);
}));
});
Run Code Online (Sandbox Code Playgroud)
以下是incrementBadgeCount增加有效负载的徽章计数并返回有效负载的一些信息的函数:
async function incrementBadgeCount(memberID: string):
Promise<MemberPushNotificaitonInfo> {
const fs = admin.firestore();
const trans = await fs.runTransaction(async transaction => {
const docRef = fs.doc(`member/${memberID}`);
return transaction.get(docRef).then(doc => {
let count: number = doc.get('badgeCount') || 0;
const ids: Object = doc.get('deviceToken');
transaction.update(docRef, {badgeCount: ++count});
const memberPayload = new MemberPushNotificaitonInfo(count, ids);
return Promise.resolve(memberPayload);
});
});
return trans
}
Run Code Online (Sandbox Code Playgroud)
最后是sendPushNotification与FCM接口并关闭有效负载并清理坏设备令牌的功能:
async function sendPushNotification(memberID: string, deviceIDs: string[], payload: any, options: any) {
if (typeof deviceIDs === 'undefined') {
console.log("member does not have deviceToken");
return Promise.resolve();
}
const response = await admin.messaging().sendToDevice(deviceIDs, payload, options);
const tokensToRemove = [];
response.results.forEach((result, index) => {
const error = result.error;
const success = result.messageId;
if (success) {
console.log("success messageID:", success);
return
}
if (error) {
const failureDeviceID = deviceIDs[index];
console.error(`error with ID: ${failureDeviceID}`, error);
if (error.code === 'messaging/invalid-registration-token' ||
error.code === 'messaging/registration-token-not-registered') {
const doc = admin.firestore().doc(`member/${memberID}`);
tokensToRemove.push(doc.update({
deviceToken: {
failureDeviceID: FieldValue.delete()
}
}));
}
}
});
return Promise.all(tokensToRemove);
}
Run Code Online (Sandbox Code Playgroud)
我会感谢一些帮助收紧这个打字稿:)
最有可能的是,您在 firebase api 上调用的某些函数应该被await编辑,但没有。我不熟悉 firebase,无法准确告诉您它是哪一个,但似乎对 firebase API 的任何调用都可能await可行。
这就是确保您为 Firebase 安装了类型定义并使用良好的编辑器的原因。查看所有 Firebase 调用并确保它们都没有秘密返回 Promise。
另外,您应该确保所有函数和变量都尽可能强类型,因为这将帮助您避免任何问题。
因此,以下几行对我来说看起来很可疑:
fs.doc(`member/${memberID}`);
transaction.update(docRef, {badgeCount: ++count});
const doc = admin.firestore().doc(`member/${memberID}`);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
280 次 |
| 最近记录: |