FCM和Typescript Async Await:网络超时问题

7

我是Typescript的新手,正在尝试使用async和await功能。偶尔会出现一些fcm网络超时问题,并且我相信这与我的promise没有正确返回有关。

这是我的发送推送通知的云函数。两个使用await关键字的函数是incrementBadgeCountsendPushNotification:

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);
  }));
});

这里是 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
}

最后,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);
}

我希望您能帮我优化这段 TypeScript 代码 :)

2个回答

0

很可能,您正在调用 Firebase API 上的某个函数,应该使用await,但没有这样做。我不熟悉 Firebase ,无法告诉您确切的函数是哪个,但似乎对 Firebase API 的任何调用都可能需要使用await

这就是确保您已安装了 Firebase 的类型定义并使用良好编辑器的地方。查看所有的 Firebase 调用,并确保它们中没有一个在秘密返回一个承诺。

此外,您还应确保尽可能强制类型化所有函数和变量,因为这将帮助您避免任何问题。

所以,以下行对我来说看起来可疑:

fs.doc(`member/${memberID}`);

transaction.update(docRef, {badgeCount: ++count});

const doc = admin.firestore().doc(`member/${memberID}`);

0
这是因为您打开了太多的HTTP连接来发送推送通知,理想情况下,您应该创建5、10等批次来发送推送。
尝试更改,
return await Promise.all(ids.map(async (id) => { ... });

至,

while(ids.length) {
    var batch = ids.splice(0, ids.length >= 5 ? 5 : ids.length);
    await Promise.all(batch.map( async (id) => { ... });
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接