Parameters adjustments + cosmetics
[vchess.git] / server / routes / games.js
... / ...
CommitLineData
1var router = require("express").Router();
2var UserModel = require("../models/User");
3var ChallengeModel = require('../models/Challenge');
4var GameModel = require('../models/Game');
5var VariantModel = require('../models/Variant');
6var access = require("../utils/access");
7var params = require("../config/parameters");
8
9// From main hall, start game between players 0 and 1
10router.post("/games", access.logged, access.ajax, (req,res) => {
11 const gameInfo = req.body.gameInfo;
12 if (!gameInfo.players.some(p => p.id == req.userId))
13 return res.json({errmsg: "Cannot start someone else's game"});
14 const cid = req.body.cid;
15 ChallengeModel.remove(cid);
16 const fen = req.body.fen;
17 GameModel.create(
18 gameInfo.vid, gameInfo.fen, gameInfo.timeControl, gameInfo.players,
19 (err,ret) => {
20 access.checkRequest(res, err, ret, "Cannot create game", () => {
21 const oppIdx = (gameInfo.players[0].id == req.userId ? 1 : 0);
22 const oppId = gameInfo.players[oppIdx].id;
23 UserModel.tryNotify(oppId,
24 "New game: " + params.siteURL + "/game/" + ret.gid);
25 res.json({gameId: ret.gid});
26 });
27 }
28 );
29});
30
31router.get("/games", access.ajax, (req,res) => {
32 const gameId = req.query["gid"];
33 if (!!gameId)
34 {
35 GameModel.getOne(gameId, (err,game) => {
36 access.checkRequest(res, err, game, "Game not found", () => {
37 res.json({game: game});
38 });
39 });
40 }
41 else
42 {
43 // Get by (non-)user ID:
44 const userId = req.query["uid"];
45 const excluded = !!req.query["excluded"];
46 GameModel.getByUser(userId, excluded, (err,games) => {
47 if (!!err)
48 return res.json({errmsg: err.errmsg || err.toString()});
49 res.json({games: games});
50 });
51 }
52});
53
54// New move + fen update + score, potentially
55// TODO: if newmove fail, takeback in GUI
56router.put("/games", access.logged, access.ajax, (req,res) => {
57 const gid = req.body.gid;
58 const obj = req.body.newObj;
59 GameModel.update(gid, obj, (err) => {
60 if (!!err)
61 return res.json(err);
62 // Notify opponent if he enabled notifications:
63 GameModel.getPlayers(gid, (err2,players) => {
64 if (!!err2)
65 return res.json(err);
66 const oppid = (players[0].id == req.userId ? players[1].id : players[0].id);
67 UserModel.tryNotify(oppid,
68 "New move in game: " + params.siteURL + "/game/" + gid);
69 });
70 res.json({});
71 });
72});
73
74module.exports = router;