Experimental multi-tabs support (TODO: prevent multi-connect)
[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 const params = require("../config/parameters");
8
9 router.get("/challenges", (req,res) => {
10 if (!req.query["uid"].match(/^[0-9]+$/))
11 res.json({errmsg: "Bad user ID"});
12 ChallengeModel.getByUser(req.query["uid"], (err,challenges) => {
13 res.json(err || {challenges:challenges});
14 });
15 });
16
17 router.post("/challenges", access.logged, access.ajax, (req,res) => {
18 const error = ChallengeModel.checkChallenge(req.body.chall);
19 if (!!error)
20 return res.json({errmsg:error});
21 let challenge =
22 {
23 fen: req.body.chall.fen,
24 cadence: req.body.chall.cadence,
25 vid: req.body.chall.vid,
26 uid: req.userId,
27 to: req.body.chall.to, //string: user name (may be empty)
28 };
29 const insertChallenge = () => {
30 ChallengeModel.create(challenge, (err,ret) => {
31 return res.json(err || {cid:ret.cid});
32 });
33 };
34 if (!!req.body.chall.to)
35 {
36 UserModel.getOne("name", challenge.to, (err,user) => {
37 if (!!err || !user)
38 return res.json(err | {errmsg: "Typo in player name"});
39 challenge.to = user.id; //ready now to insert challenge
40 insertChallenge();
41 if (user.notify)
42 UserModel.notify(user, "New challenge: " + params.siteURL + "/");
43 });
44 }
45 else
46 insertChallenge();
47 });
48
49 router.delete("/challenges", access.logged, access.ajax, (req,res) => {
50 const cid = req.query.id;
51 if (!cid.match(/^[0-9]+$/))
52 res.json({errmsg: "Bad challenge ID"});
53 ChallengeModel.safeRemove(cid, req.userId, err => {
54 res.json(err || {}); //TODO: just "return err" because is empty if no errors
55 });
56 });
57
58 module.exports = router;