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