zhao/imports/api/methods/newGame.js

41 lines
1,013 B
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 06:36:02 +00:00
"newGame": async ({ name }) => {
2020-11-27 05:59:25 +00:00
check(name, String);
2020-11-27 06:36:02 +00:00
let roomId = null;
let state = "waitingRoom";
// attempt to get a valid room code 10 times
let remainingAttempts = 10;
let joinCode;
while (roomId === null && remainingAttempts > 0) {
joinCode = Random.hexString(6);
let started = new Date();
try {
let result = Rooms.insert({ joinCode, started, state });
roomId = result;
break;
} catch (e) {
// BulkWriteError
if (e.code === 11000) {
remainingAttempts -= 1;
}
}
}
let playerId = Players.insert({ roomId, name });
if (remainingAttempts == 0 && roomId === null) {
return "failed";
}
return { playerId, roomId, joinCode };
2020-11-27 05:59:25 +00:00
},
});