48 lines
1.3 KiB
JavaScript
48 lines
1.3 KiB
JavaScript
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";
|
|
|
|
Meteor.methods({
|
|
"newGame": ({ name }) => {
|
|
check(name, String);
|
|
name = name.trim();
|
|
|
|
let roomId = undefined;
|
|
let state = "waitingRoom";
|
|
|
|
// attempt to get a valid room code 10 times
|
|
let remainingAttempts = 10;
|
|
let joinCode;
|
|
while (roomId === undefined && remainingAttempts > 0) {
|
|
joinCode = Random.hexString(6).toLowerCase();
|
|
let started = new Date();
|
|
|
|
try {
|
|
let result = Rooms.insert({ joinCode, started, state });
|
|
roomId = result;
|
|
break;
|
|
} catch (e) {
|
|
// BulkWriteError
|
|
if (e.code === 11000) {
|
|
} else {
|
|
console.log("UNCAUGHT", e);
|
|
}
|
|
}
|
|
remainingAttempts -= 1;
|
|
}
|
|
|
|
console.log("ROOM ID", roomId);
|
|
let playerId = Players.insert({ roomId, name });
|
|
Rooms.update(roomId, { $set: { owner: playerId } });
|
|
|
|
if (remainingAttempts == 0 && roomId === undefined) {
|
|
throw new Meteor.Error("no-more-rooms");
|
|
}
|
|
|
|
let players = {};
|
|
players[playerId] = name;
|
|
return { players, roomId, joinCode };
|
|
},
|
|
});
|