如何使用打字稿在Firebase函数中遍历实时数据库

时间:2018-10-01 17:37:27

标签: typescript firebase firebase-realtime-database

我是Firebase云功能的新手。我正在尝试使用代码

进行迭代
export const onPlay = functions.https.onRequest((req, res) => {
    const token = req.query.token
    let opponent: Player

    const playersRef = admin.database().ref("players")
    playersRef.once("value", snapshot => {
        snapshot.forEach(data => {
            opponent = data.val()
            if(token !== opponent.token){
                // return opponent
            }
        })
    })
    .then(opp=> {
        res.send("Hello from " + opp.name)
    })

})

但是forEach必须返回布尔值

forEach(action: (a: admin.database.DataSnapshot) => boolean): boolean

1 个答案:

答案 0 :(得分:1)

只需在循环末尾抛出return false;就可以了:

export const onPlay = functions.https.onRequest((req, res) => {
const token = req.query.token
let opponent: Player

const playersRef = admin.database().ref("players")

playersRef.once("value", snapshot => {

    snapshot.forEach(data => {

        opponent = data.val()

        if(token !== opponent.token)
        {
            // return opponent
        }

       return false; // <-----------
    });

}).then(opp=> {
    res.send("Hello from " + opp.name)
   });

});