Fix Koopa chess + select only required fields in userMode.getOne()
[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) {
fccaa878
BA
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 }
866842c3 36 }
fccaa878 37 );
0234201f 38 } else insertChallenge();
866842c3
BA
39 }
40});
41
42router.get("/challenges", access.ajax, (req,res) => {
43 const uid = req.query.uid;
0234201f 44 if (uid.match(/^[0-9]+$/)) {
866842c3 45 ChallengeModel.getByUser(uid, (err,challenges) => {
0234201f 46 res.json(err || { challenges: challenges });
bf20f404 47 });
bf20f404 48 }
4edfed6c
BA
49});
50
1f49533d 51router.delete("/challenges", access.logged, access.ajax, (req,res) => {
77fd7298 52 const cid = req.query.id;
0234201f 53 if (cid.match(/^[0-9]+$/)) {
866842c3
BA
54 ChallengeModel.safeRemove(cid, req.userId);
55 res.json({});
56 }
1f49533d 57});
8d7e2786
BA
58
59module.exports = router;