zhao/imports/api/methods/joinGame.js

41 lines
1,017 B
JavaScript
Raw Normal View History

2020-11-27 07:16:15 +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";
Meteor.methods({
"joinGame": async ({ code, name }) => {
check(code, String);
check(name, String);
name = name.trim();
2020-11-27 07:34:12 +00:00
let room = Rooms.findOne({ joinCode: code.toLowerCase() });
2020-11-27 07:16:15 +00:00
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;
2020-11-27 08:18:29 +00:00
if (roomId === undefined) {
throw new Meteor.Error("room-id-undefined");
}
2020-11-27 08:44:06 +00:00
let level = 2;
let playerId;
2020-11-27 07:16:15 +00:00
try {
2020-11-27 08:44:06 +00:00
playerId = Players.insert({ roomId, name, level });
2020-11-27 07:16:15 +00:00
} catch (e) {
if (e.code === 11000) {
throw new Meteor.Error("name-collision");
}
}
let joinCode = room.joinCode;
2020-11-27 08:44:06 +00:00
return { joinCode, playerId, roomId };
2020-11-27 07:16:15 +00:00
}
});