Fix Koopa chess + select only required fields in userMode.getOne()
[vchess.git] / server / routes / challenges.js
... / ...
CommitLineData
1let router = require("express").Router();
2const access = require("../utils/access");
3const ChallengeModel = require("../models/Challenge");
4const UserModel = require("../models/User"); //for name check
5const params = require("../config/parameters");
6
7router.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 } else insertChallenge();
39 }
40});
41
42router.get("/challenges", access.ajax, (req,res) => {
43 const uid = req.query.uid;
44 if (uid.match(/^[0-9]+$/)) {
45 ChallengeModel.getByUser(uid, (err,challenges) => {
46 res.json(err || { challenges: challenges });
47 });
48 }
49});
50
51router.delete("/challenges", access.logged, access.ajax, (req,res) => {
52 const cid = req.query.id;
53 if (cid.match(/^[0-9]+$/)) {
54 ChallengeModel.safeRemove(cid, req.userId);
55 res.json({});
56 }
57});
58
59module.exports = router;