zhao/imports/api/methods/newGame.js

52 lines
1.3 KiB
JavaScript
Raw Normal View History

2020-11-27 06:36:02 +00:00
import { Meteor } from "meteor/meteor";
import { Random } from "meteor/random";
import { check } from "meteor/check";
import Rooms from "../collections/Rooms.js";
import Players from "../collections/Players.js";
2020-11-27 05:59:25 +00:00
Meteor.methods({
2020-11-27 08:18:29 +00:00
"newGame": ({ name }) => {
2020-11-27 05:59:25 +00:00
check(name, String);
2020-11-27 07:16:15 +00:00
name = name.trim();
2020-11-27 08:18:29 +00:00
let roomId = undefined;
2020-11-27 06:36:02 +00:00
let state = "waitingRoom";
2020-11-27 08:23:31 +00:00
let ruleset = {
decks: 2,
};
2020-11-27 06:36:02 +00:00
// attempt to get a valid room code 10 times
let remainingAttempts = 10;
let joinCode;
2020-11-27 08:18:29 +00:00
while (roomId === undefined && remainingAttempts > 0) {
2020-11-27 07:34:12 +00:00
joinCode = Random.hexString(6).toLowerCase();
2020-11-27 06:36:02 +00:00
let started = new Date();
try {
2020-11-27 08:23:31 +00:00
let result = Rooms.insert({ joinCode, started, state, ruleset });
2020-11-27 06:36:02 +00:00
roomId = result;
break;
} catch (e) {
// BulkWriteError
if (e.code === 11000) {
2020-11-27 07:16:15 +00:00
} else {
console.log("UNCAUGHT", e);
2020-11-27 06:36:02 +00:00
}
}
2020-11-27 08:18:29 +00:00
remainingAttempts -= 1;
2020-11-27 06:36:02 +00:00
}
2020-11-27 08:18:29 +00:00
console.log("ROOM ID", roomId);
2020-11-27 06:36:02 +00:00
let playerId = Players.insert({ roomId, name });
2020-11-27 07:16:15 +00:00
Rooms.update(roomId, { $set: { owner: playerId } });
2020-11-27 06:36:02 +00:00
2020-11-27 08:18:29 +00:00
if (remainingAttempts == 0 && roomId === undefined) {
2020-11-27 07:16:15 +00:00
throw new Meteor.Error("no-more-rooms");
2020-11-27 06:36:02 +00:00
}
2020-11-27 07:16:15 +00:00
let players = {};
players[playerId] = name;
return { players, roomId, joinCode };
2020-11-27 05:59:25 +00:00
},
});