Work on correspondance challenges system
[vchess.git] / server / routes / challenges.js
1 // AJAX methods to get, create, update or delete a challenge
2
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
7
8 router.delete("/testtest", access.ajax, (req,res) => {
9 console.log("passag");
10 ChallengeModel.testfunc();
11 });
12
13 router.post("/challenges", access.logged, access.ajax, (req,res) => {
14 const error = ChallengeModel.checkChallenge(req.body.chall);
15 if (!!error)
16 return res.json({errmsg:error});
17 const challenge =
18 {
19 fen: req.body.chall.fen,
20 timeControl: req.body.chall.timeControl,
21 vid: req.body.chall.vid,
22 uid: req.userId,
23 nbPlayers: req.body.chall.to.length,
24 };
25 ChallengeModel.create(challenge, (err,lastId) => {
26 if (!!err)
27 return res.json(err);
28 if (!!req.body.chall.to[0])
29 {
30 UserModel.getByName(req.body.chall.to, (err,users) => {
31 if (!!err)
32 return res.json(err);
33 if (users.length < req.body.chall.to.length)
34 return res.json({errmsg: "Typo in player(s) name(s)"});
35 ChallengeModel.initializeWillPlay(
36 users.map(u => u.id),
37 lastId["rowid"],
38 (err) => {
39 if (!!err)
40 return res.json(err);
41 res.json({cid: lastId["rowid"]});
42 }
43 );
44 });
45 }
46 else
47 res.json({cid: lastId["rowid"]});
48 });
49 });
50
51 //// index
52 //router.get("/challenges", access.logged, access.ajax, (req,res) => {
53 // if (req.query["uid"] != req.user._id)
54 // return res.json({errmsg: "Not your challenges"});
55 // let uid = ObjectID(req.query["uid"]);
56 // ChallengeModel.getByPlayer(uid, (err, challengeArray) => {
57 // res.json(err || {challenges: challengeArray});
58 // });
59 //});
60 //
61 //function createChallenge(vid, from, to, res)
62 //{
63 // ChallengeModel.create(vid, from, to, (err, chall) => {
64 // res.json(err || {
65 // // A challenge can be sent using only name, thus 'to' is returned
66 // to: chall.to,
67 // cid: chall._id
68 // });
69 // });
70 //}
71
72 router.delete("/challenges", access.logged, access.ajax, (req,res) => {
73 const cid = req.query.cid;
74 ChallengeModel.remove(cid, req.userId, err => {
75 res.json(err || {});
76 });
77 });
78
79 module.exports = router;