Work on correspondance challenges system
[vchess.git] / server / routes / challenges.js
CommitLineData
ab4f4bf2 1// AJAX methods to get, create, update or delete a challenge
582df349 2
ab4f4bf2
BA
3let router = require("express").Router();
4const access = require("../utils/access");
5const ChallengeModel = require("../models/Challenge");
052d17ea 6const UserModel = require("../models/User"); //for name check
8d7e2786 7
36093eba
BA
8router.delete("/testtest", access.ajax, (req,res) => {
9 console.log("passag");
10 ChallengeModel.testfunc();
11});
12
052d17ea 13router.post("/challenges", access.logged, access.ajax, (req,res) => {
1f49533d
BA
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 });
8d7e2786
BA
49});
50
ab4f4bf2 51//// index
f4f4c03c 52//router.get("/challenges", access.logged, access.ajax, (req,res) => {
1f49533d
BA
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// });
ab4f4bf2
BA
59//});
60//
61//function createChallenge(vid, from, to, res)
62//{
1f49533d
BA
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// });
ab4f4bf2 70//}
1f49533d
BA
71
72router.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});
8d7e2786
BA
78
79module.exports = router;