Reputation: 1
I've started using Firebase recently with my Unity game to create a simple turnbased game. First time using Firebase functions as well, not to mention not that skilled in JS.
I'm using this code that handles a simple matchmaking system for newly added players to the matchmaking sub-database and match them with other players who are idle, then creates a random id for the game set it to them and then creates a new object in a "games" sub-database.
I've uploaded the core to Firebase and started testing it manually on the real-time database by adding "users" but it's not working and the log says :
Function returned undefined, expected Promise or value
I've looked online to find out what to do but I'm lost about "Promises" I'd appreciate help in this matter.
Here's the JS code:
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp(functions.config().firebase);
const database = admin.database();
exports.matchmaker = functions.database.ref("matchmaking/{playerId}")
.onCreate((snap, context) => {
const gameId = generateGameId();
database.ref("matchmaking").once("value").then((players) => {
let secondPlayer = null;
players.forEach((player) => {
if (player.val() == "searching" &&
player.key !== context.params.playerId) {
secondPlayer = player;
}
});
if (secondPlayer === null) return null;
database.ref("matchmaking").transaction(function(matchmaking) {
if (matchmaking === null ||
matchmaking[context.params.playerId] !== "" ||
matchmaking[secondPlayer.key] !== "searching") {
return matchmaking;
}
matchmaking[context.params.playerId] = gameId;
matchmaking[secondPlayer.key] = gameId;
return matchmaking;
}).then((result) => {
if (result.snapshot.child(
context.params.playerId).val() !== gameId) {
return null;
}
const game = {
gameInfo: {
gameId: gameId,
playersIds: [context.params.playerId, secondPlayer.key],
},
turn: context.params.playerId,
};
database.ref("games/" + gameId).set(game).then((snapshot) => {
console.log("Game created successfully!");
return null;
}).catch((error) => {
console.log(error);
});
return null;
}).catch((error) => {
console.log(error);
});
return null;
}).catch((error) => {
console.log(error);
});
});
/**
* Generates random game id
* @return {int} Game id
*/
function generateGameId() {
const possibleChars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
let gameId = "";
for (let j = 0; j < 20; j++) {
gameId +=
possibleChars.charAt(Math.floor(Math.random() * possibleChars.length));
}
return gameId;
}
UPDATE: I was able to fix it by adding a return value at the end of the onCreate method.
return context.
Upvotes: 0
Views: 116
Reputation: 1
I fixed it by adding "return context" at the of the onCreate method.
Upvotes: 0