Vamsi Challa
Vamsi Challa

Reputation: 11109

Nodejs cloud functions - Not all code paths return a value

I am writing a cloud function to create a node in firebase realtime database. The code seems to be returning a value for all paths. Where is it that i am going wrong? Is there a scenario where gamesRef.push() is not called and is that the reason the error is being thrown?

Cloud Function:

export const createGame = functions.https.onCall((data, context) => {

    const game_type = data.game_type;
    if (game_type != GAME_PRACTISE || game_type != GAME_MULTIPLAYER || game_type != GAME_FRIENDS) {
        return {
            "status": 403,
            "id": null
        };
    } else {

        const uid = data.uid;
        const status = GAME_STATUS_OPEN;
        var players = [uid];

        let max_players;
        if (game_type == GAME_PRACTISE) {
            max_players = 1;
        } else if (game_type == GAME_MULTIPLAYER) {
            max_players = 10;
        } else if (game_type == GAME_FRIENDS) {
            max_players = 50;
        }

        let db = admin.database();
        let gamesRef = db.ref("/games");

        gamesRef.push({
            ... // data to be inserted
        }).then(res => {
            return {
                "status": 200,
                "id": gamesRef.key
            }
        }).catch(error => {
            return {
                "status": 403,
                "id": null
            }
        });

    }
});


Upvotes: 0

Views: 76

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598688

You're missing a return here:

return gamesRef.push({
    ... // data to be inserted
}).then(res => {
    return {
        "status": 200,
        "id": gamesRef.key
    }
}).catch(error => {
    return {
        "status": 403,
        "id": null
    }
});

Without that top-level return, nobody will ever see the return values from your then and catch callbacks.

Upvotes: 1

Related Questions