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