Add a new variant in TODO
[vchess.git] / server / routes / challenges.js
CommitLineData
ab4f4bf2
BA
1let router = require("express").Router();
2const access = require("../utils/access");
3const ChallengeModel = require("../models/Challenge");
052d17ea 4const UserModel = require("../models/User"); //for name check
fe4c7e67 5const params = require("../config/parameters");
8d7e2786 6
052d17ea 7router.post("/challenges", access.logged, access.ajax, (req,res) => {
866842c3 8 if (ChallengeModel.checkChallenge(req.body.chall))
1f49533d 9 {
866842c3
BA
10 let challenge =
11 {
12 fen: req.body.chall.fen,
13 cadence: req.body.chall.cadence,
14 vid: req.body.chall.vid,
15 uid: req.userId,
16 to: req.body.chall.to, //string: user name (may be empty)
17 };
18 const insertChallenge = () => {
19 ChallengeModel.create(challenge, (err,ret) => {
20 res.json(err || {cid:ret.cid});
21 });
22 };
23 if (req.body.chall.to)
24 {
25 UserModel.getOne("name", challenge.to, (err,user) => {
26 if (!!err || !user)
27 res.json(err || {errmsg: "Typo in player name"});
28 else
29 {
30 challenge.to = user.id; //ready now to insert challenge
31 insertChallenge();
32 if (user.notify)
33 UserModel.notify(
34 user,
35 "New challenge: " + params.siteURL + "/#/?disp=corr");
36 }
37 });
38 }
39 else
bebcc8d4 40 insertChallenge();
866842c3
BA
41 }
42});
43
44router.get("/challenges", access.ajax, (req,res) => {
45 const uid = req.query.uid;
46 if (uid.match(/^[0-9]+$/))
47 {
48 ChallengeModel.getByUser(uid, (err,challenges) => {
49 res.json(err || {challenges:challenges});
bf20f404 50 });
bf20f404 51 }
4edfed6c
BA
52});
53
1f49533d 54router.delete("/challenges", access.logged, access.ajax, (req,res) => {
77fd7298 55 const cid = req.query.id;
866842c3
BA
56 if (cid.match(/^[0-9]+$/))
57 {
58 ChallengeModel.safeRemove(cid, req.userId);
59 res.json({});
60 }
1f49533d 61});
8d7e2786
BA
62
63module.exports = router;