1 // AJAX methods to get, create, update or delete a challenge
3 let router
= require("express").Router();
4 const access
= require("../utils/access");
5 const ChallengeModel
= require("../models/Challenge");
6 const UserModel
= require("../models/User"); //for name check
8 router
.get("/challenges", (req
,res
) => {
9 ChallengeModel
.getByUser(req
.query
["uid"], (err
,challenges
) => {
10 res
.json(err
|| {challenges:challenges
});
14 router
.post("/challenges", access
.logged
, access
.ajax
, (req
,res
) => {
15 const error
= ChallengeModel
.checkChallenge(req
.body
.chall
);
17 return res
.json({errmsg:error
});
20 fen: req
.body
.chall
.fen
,
21 timeControl: req
.body
.chall
.timeControl
,
22 vid: req
.body
.chall
.vid
,
24 nbPlayers: req
.body
.chall
.to
.length
,
26 ChallengeModel
.create(challenge
, (err
,lastId
) => {
29 if (!!req
.body
.chall
.to
[0])
31 UserModel
.getByName(req
.body
.chall
.to
, (err
,users
) => {
34 if (users
.length
< req
.body
.chall
.to
.length
)
35 return res
.json({errmsg: "Typo in player(s) name(s)"});
36 ChallengeModel
.initializeWillPlay(
42 res
.json({cid: lastId
["rowid"]});
48 res
.json({cid: lastId
["rowid"]});
52 // Nothing to do if challenge is refused (just removal)
53 router
.put("/challenges", access
.logged
, access
.ajax
, (req
,res
) => {
54 switch (req
.body
.action
)
57 // turn WillPlay to false (TODO?)
60 // turn WillPlay to true; if then challenge is full, launch game
61 ChallengeModel
.getSeatCount(req
.body
.id
, (scount
) => {
63 launchGame(req
.body
.id
, req
.userId
);
65 ChallengeModel
.setSeat(req
.body
.id
, req
.userId
);
72 function launchGame(cid
, uid
)
74 // TODO: gather challenge infos + WillPlay
75 // Then create game, and remove challenge + WillPlay
79 //router.get("/challenges", access.logged, access.ajax, (req,res) => {
80 // if (req.query["uid"] != req.user._id)
81 // return res.json({errmsg: "Not your challenges"});
82 // let uid = ObjectID(req.query["uid"]);
83 // ChallengeModel.getByPlayer(uid, (err, challengeArray) => {
84 // res.json(err || {challenges: challengeArray});
88 //function createChallenge(vid, from, to, res)
90 // ChallengeModel.create(vid, from, to, (err, chall) => {
92 // // A challenge can be sent using only name, thus 'to' is returned
99 router
.delete("/challenges", access
.logged
, access
.ajax
, (req
,res
) => {
100 const cid
= req
.query
.id
;
101 ChallengeModel
.remove(cid
, req
.userId
, err
=> {
106 module
.exports
= router
;