efc697011d408340ce05d32103b4e8f9512cbfea
[vchess.git] / server / routes / challenges.js
1 let router = require("express").Router();
2 const access = require("../utils/access");
3 const ChallengeModel = require("../models/Challenge");
4 const UserModel = require("../models/User"); //for name check
5 const params = require("../config/parameters");
6
7 router.post("/challenges", access.logged, access.ajax, (req,res) => {
8 if (ChallengeModel.checkChallenge(req.body.chall))
9 {
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
40 insertChallenge();
41 }
42 });
43
44 router.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});
50 });
51 }
52 });
53
54 router.delete("/challenges", access.logged, access.ajax, (req,res) => {
55 const cid = req.query.id;
56 if (cid.match(/^[0-9]+$/))
57 {
58 ChallengeModel.safeRemove(cid, req.userId);
59 res.json({});
60 }
61 });
62
63 module.exports = router;