当调用admin.firestore()时,Firebase Cloud Function没有console.log

时间:2019-11-07 01:40:44

标签: node.js typescript firebase google-cloud-firestore google-cloud-functions

我有一个Webhook可以通过云功能接收Facebook Messenger事件:

export const facebookMessengerHook = functions.https.onRequest(async (req: express.Request, res: express.Response) => {
    console.log(req);
    console.log(req.method);
    console.log(req.body);
    if (req.method == "POST") {
        const body = req.body;

        console.log(body);
        // Checks this is an event from a page subscription
        if (body.object === 'page') {
            res.status(200).send('EVENT_RECEIVED');

            // Iterates over each entry - there may be multiple if batched
            for (const entry of body.entry) {
                // will only ever contain one message, so we get index 0
                const webhook_data = entry.messaging[0];

                console.log(webhook_data);
                try {
                    // v THAT PART HERE v
                    const user = await admin.firestore().collection('users')
                        .where('facebookMessengerId', '==', webhook_data.sender.id)
                        .get();
                    // ^ THAT PART HERE ^
                    console.log(user);
                } catch (e) {
                    console.log('No user');
                }
            }
        }
        else {
            // Returns a '404 Not Found' if event is not from a page subscription
            res.sendStatus(404);
        }
    }
});

除非我注释掉代码段中标记的部分,否则它不会记录任何内容。

有人可以向我解释为什么以及如何解决此问题,因为我需要打电话给firestore,并且还需要console.log进行调试?

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

问题很可能来自这样的事实

res.status(200).send('EVENT_RECEIVED');

您实际上向Cloud Function平台指示可以完成其余的异步工作(对get()方法的调用集)之前终止Cloud Function。请参阅以下官方video表格以获取更多详细信息。换句话说,在get()方法返回的承诺被解决之前,Cloud Function已终止。

因此,您应该按如下所示修改代码:

    //....
    if (body.object === 'page') {


        // Iterates over each entry - there may be multiple if batched
        for (const entry of body.entry) {
            // will only ever contain one message, so we get index 0
            const webhook_data = entry.messaging[0];

            console.log(webhook_data);
            try {

                const user = await admin.firestore().collection('users')
                    .where('facebookMessengerId', '==', webhook_data.sender.id)
                    .get();

                console.log(user);


            } catch (e) {
                console.log('No user');
                //Here throw an error to be catched at an upper level
            }
        }

        res.status(200).send('EVENT_RECEIVED');
    }
    //....

请注意,由于您对数据库进行了一系列提取,因此可以使用Promise.all()。但是用您的代码无法确认这一点,因为它没有显示出这些提取的确切用法。