Commit | Line | Data |
---|---|---|
ab4f4bf2 | 1 | // AJAX methods to get, create, update or delete a challenge |
582df349 | 2 | |
ab4f4bf2 BA |
3 | let router = require("express").Router(); |
4 | const access = require("../utils/access"); | |
5 | const ChallengeModel = require("../models/Challenge"); | |
052d17ea | 6 | const UserModel = require("../models/User"); //for name check |
8d7e2786 | 7 | |
f05815d7 | 8 | router.get("/challenges", (req,res) => { |
4edfed6c BA |
9 | ChallengeModel.getByUser(req.query["uid"], (err,challenges) => { |
10 | res.json(err || {challenges:challenges}); | |
11 | }); | |
12 | }); | |
13 | ||
052d17ea | 14 | router.post("/challenges", access.logged, access.ajax, (req,res) => { |
1f49533d BA |
15 | const error = ChallengeModel.checkChallenge(req.body.chall); |
16 | if (!!error) | |
17 | return res.json({errmsg:error}); | |
bf20f404 | 18 | let challenge = |
1f49533d BA |
19 | { |
20 | fen: req.body.chall.fen, | |
21 | timeControl: req.body.chall.timeControl, | |
22 | vid: req.body.chall.vid, | |
23 | uid: req.userId, | |
bf20f404 | 24 | to: req.body.chall.to, //string: user name (may be empty) |
1f49533d | 25 | }; |
bf20f404 | 26 | const insertChallenge = () => { |
b4de2e73 BA |
27 | ChallengeModel.create(challenge, (err,ret) => { |
28 | return res.json(err || {cid:ret.cid}); | |
bf20f404 BA |
29 | }); |
30 | }; | |
31 | if (!!req.body.chall.to) | |
32 | { | |
33 | UserModel.getOne("name", challenge.to, (err,user) => { | |
34 | if (!!err || !user) | |
35 | return res.json(err | {errmsg: "Typo in player name"}); | |
36 | challenge.to = user.id; //ready now to insert challenge | |
bebcc8d4 | 37 | insertChallenge(); |
bf20f404 | 38 | }); |
bf20f404 BA |
39 | } |
40 | else | |
41 | insertChallenge(); | |
4edfed6c BA |
42 | }); |
43 | ||
1f49533d | 44 | router.delete("/challenges", access.logged, access.ajax, (req,res) => { |
77fd7298 | 45 | const cid = req.query.id; |
2be5d614 | 46 | ChallengeModel.safeRemove(cid, req.userId, err => { |
b1aa927b | 47 | res.json(err || {}); //TODO: just "return err" because is empty if no errors |
1f49533d BA |
48 | }); |
49 | }); | |
8d7e2786 BA |
50 | |
51 | module.exports = router; |