1 // AJAX methods to get, create, update or delete a challenge
3 let router
= require("express").Router();
4 const access
= require("../utils/access");
5 const ChallengeModel
= require("../models/Challenge");
6 const UserModel
= require("../models/User"); //for name check
7 const params
= require("../config/parameters");
9 router
.get("/challenges", (req
,res
) => {
10 if (!req
.query
["uid"].match(/^[0-9]+$/))
11 res
.json({errmsg: "Bad user ID"});
12 ChallengeModel
.getByUser(req
.query
["uid"], (err
,challenges
) => {
13 res
.json(err
|| {challenges:challenges
});
17 router
.post("/challenges", access
.logged
, access
.ajax
, (req
,res
) => {
18 const error
= ChallengeModel
.checkChallenge(req
.body
.chall
);
20 return res
.json({errmsg:error
});
23 fen: req
.body
.chall
.fen
,
24 cadence: req
.body
.chall
.cadence
,
25 vid: req
.body
.chall
.vid
,
27 to: req
.body
.chall
.to
, //string: user name (may be empty)
29 const insertChallenge
= () => {
30 ChallengeModel
.create(challenge
, (err
,ret
) => {
31 return res
.json(err
|| {cid:ret
.cid
});
34 if (!!req
.body
.chall
.to
)
36 UserModel
.getOne("name", challenge
.to
, (err
,user
) => {
38 return res
.json(err
| {errmsg: "Typo in player name"});
39 challenge
.to
= user
.id
; //ready now to insert challenge
42 UserModel
.notify(user
, "New challenge: " + params
.siteURL
+ "/");
49 router
.delete("/challenges", access
.logged
, access
.ajax
, (req
,res
) => {
50 const cid
= req
.query
.id
;
51 if (!cid
.match(/^[0-9]+$/))
52 res
.json({errmsg: "Bad challenge ID"});
53 ChallengeModel
.safeRemove(cid
, req
.userId
, err
=> {
54 res
.json(err
|| {}); //TODO: just "return err" because is empty if no errors
58 module
.exports
= router
;