Replace news by FAQ
[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("name", challenge.to, (err,user) => {
24 if (err || !user)
25 res.json(err || {errmsg: "Typo in player name"});
26 else {
27 challenge.to = user.id; //ready now to insert challenge
28 insertChallenge();
29 if (user.notify)
30 UserModel.notify(
31 user,
32 "New challenge : " + params.siteURL + "/#/?disp=corr");
33 }
34 });
35 } else insertChallenge();
36 }
37 });
38
39 router.get("/challenges", access.ajax, (req,res) => {
40 const uid = req.query.uid;
41 if (uid.match(/^[0-9]+$/)) {
42 ChallengeModel.getByUser(uid, (err,challenges) => {
43 res.json(err || { challenges: challenges });
44 });
45 }
46 });
47
48 router.delete("/challenges", access.logged, access.ajax, (req,res) => {
49 const cid = req.query.id;
50 if (cid.match(/^[0-9]+$/)) {
51 ChallengeModel.safeRemove(cid, req.userId);
52 res.json({});
53 }
54 });
55
56 module.exports = router;