【发布时间】:2020-07-25 12:10:21
【问题描述】:
场景是当玩家在应用中点击“加入游戏”时,会调用云函数将玩家添加到 Firebase 数据库,并将结果作为响应传递。
数据库结构:
/games
|--/game_id
|----/players => this is a json array of uids and their status([{"uid1": true}, {"uid2":true},...])
|----/max_players = 10
云函数应该检查 /players 的大小是否小于 /max_players,如果是,它应该使用播放器的 uid 更新 /players 并返回响应。
这是我的云功能:
export const addUserToGame = functions.https.onCall((data, context) => {
// Expected inputs - game_id(from data) and UID(from context)
if (context.auth == null) {
return {
"status": 403,
"message": "You are not authorized to access this feature"
};
}
const uid = context.auth.uid;
const game_id = data.game_id;
let gameIDRef = gamesRef.child(game_id);
return gameIDRef.transaction(function (t) {
if (t === null) {
// don't do anything, can i just do return;
} else {
let playersNode;
let isAlreadyPlayer = false;
if (t.players) {
console.log("players is not empty");
playersNode = t.players;
let players_count = playersNode.length;
let max_players: Number = t.max_players;
if (players_count >= max_players) {
// how can i return an error from here?
}
for (var i = 0; i < playersNode.length; i++) {
if (playersNode[i].uid === uid) {
isAlreadyPlayer = true;
}
break;
}
if (!isAlreadyPlayer) {
playersNode.push({
[uid]: "active"
});
}
t.players = playersNode;
return t;
} else {
playersNode = [];
playersNode.push({
[uid]: "active"
});
t.players = playersNode;
return t;
}
}
},function(error, committed, snapshot) {
if(committed) {
return {
"status": 200,
"message": "Player added successfully"
};
} else {
return {
"status": 403,
"message": "Error adding player to the game"
};
}
});
});
请看上面代码中的cmets,当条件失败时我如何发回响应?
感谢@Doug 和@Renaud 的快速回复,我还有几个问题:
第一季度。所以我必须使用
return gameIDRef.transaction(t => {
}).then(result => {
}).catch(error => {
});
但是什么时候使用呢?这是@Renaud 指的回调版本吗?
function (error, committed, snapshot) {
});
第二季度。第一种方式,当调用gameIDRef.transaction(t => {})时,当game_id没有值和game_id没有值时会发生什么,我想告诉用户没有游戏那个指定的 id。我怎样才能做到这一点?
return gameIDRef.transaction(t => {
if(t === null)
return;
//Where does the control go from here? To then?
// Also i have a conditional check in my logic, which is to make sure the numbers of players doesn't exceed the max_players before adding the player
t.players = where the existing players are stored
t.max_players = maximum number of players a game can have
if(t.players.length >= t.max_players)
// How do i send back a message to client saying that the game is full?
// Throw an error like this?
throw new functions.https.HttpsError('failed-condition', 'The game is already full');
}).then(result => {
}).catch(error => {
// and handle it here to send message to client?
});
【问题讨论】:
标签: javascript node.js firebase firebase-realtime-database google-cloud-functions