Refactor models (merge Players in Games), add cursor to correspondance games. Finishe...
[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) => {
0234201f
BA
8 if (ChallengeModel.checkChallenge(req.body.chall)) {
9 let challenge = {
866842c3
BA
10 fen: req.body.chall.fen,
11 cadence: req.body.chall.cadence,
7ba4a5bc 12 randomness: req.body.chall.randomness,
866842c3
BA
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 = () => {
0234201f
BA
18 ChallengeModel.create(challenge, (err, ret) => {
19 res.json(err || ret);
866842c3
BA
20 });
21 };
0234201f 22 if (req.body.chall.to) {
866842c3 23 UserModel.getOne("name", challenge.to, (err,user) => {
51145f8c 24 if (err || !user)
866842c3 25 res.json(err || {errmsg: "Typo in player name"});
0234201f 26 else {
866842c3
BA
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 });
0234201f 35 } else insertChallenge();
866842c3
BA
36 }
37});
38
39router.get("/challenges", access.ajax, (req,res) => {
40 const uid = req.query.uid;
0234201f 41 if (uid.match(/^[0-9]+$/)) {
866842c3 42 ChallengeModel.getByUser(uid, (err,challenges) => {
0234201f 43 res.json(err || { challenges: challenges });
bf20f404 44 });
bf20f404 45 }
4edfed6c
BA
46});
47
1f49533d 48router.delete("/challenges", access.logged, access.ajax, (req,res) => {
77fd7298 49 const cid = req.query.id;
0234201f 50 if (cid.match(/^[0-9]+$/)) {
866842c3
BA
51 ChallengeModel.safeRemove(cid, req.userId);
52 res.json({});
53 }
1f49533d 54});
8d7e2786
BA
55
56module.exports = router;