zhao/imports/api/methods/joinGame.js
2020-11-27 02:44:06 -06:00

40 lines
1,017 B
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({
"joinGame": async ({ code, name }) => {
check(code, String);
check(name, String);
name = name.trim();
let room = Rooms.findOne({ joinCode: code.toLowerCase() });
if (room === undefined) {
throw new Meteor.Error("room-not-found");
}
if (room.state !== "waitingRoom") {
throw new Meteor.Error("room-already-playing");
}
let roomId = room._id;
if (roomId === undefined) {
throw new Meteor.Error("room-id-undefined");
}
let level = 2;
let playerId;
try {
playerId = Players.insert({ roomId, name, level });
} catch (e) {
if (e.code === 11000) {
throw new Meteor.Error("name-collision");
}
}
let joinCode = room.joinCode;
return { joinCode, playerId, roomId };
}
});