02088357c30a0bfc637141cffd6749f0e792f5ef
[vchess.git] / server / routes / problems.js
1 // AJAX methods to get, create, update or delete a problem
2
3 let router = require("express").Router();
4 const access = require("../utils/access");
5 const ProblemModel = require("../models/Problem");
6 const sanitizeHtml = require('sanitize-html');
7
8 router.get("/problems", (req,res) => {
9 const probId = req.query["pid"];
10 if (!!probId)
11 {
12 if (!probId.match(/^[0-9]+$/))
13 return res.json({errmsg: "Wrong problem ID"});
14 ProblemModel.getOne(req.query["pid"], (err,problem) => {
15 access.checkRequest(res, err, problem, "Problem not found", () => {
16 res.json({problem: problem});
17 });
18 });
19 }
20 else
21 {
22 ProblemModel.getAll((err,problems) => {
23 res.json(err || {problems:problems});
24 });
25 }
26 });
27
28 router.post("/problems", access.logged, access.ajax, (req,res) => {
29 const error = ProblemModel.checkProblem(req.body.prob);
30 if (!!error)
31 return res.json({errmsg:error});
32 const problem =
33 {
34 vid: req.body.prob.vid,
35 fen: req.body.prob.fen,
36 uid: req.userId,
37 instruction: sanitizeHtml(req.body.prob.instruction),
38 solution: sanitizeHtml(req.body.prob.solution),
39 };
40 ProblemModel.create(problem, (err,ret) => {
41 return res.json(err || {id:ret.pid});
42 });
43 });
44
45 router.put("/problems", access.logged, access.ajax, (req,res) => {
46 let obj = req.body.prob;
47 const error = ProblemModel.checkProblem(obj);
48 if (!!error)
49 return res.json({errmsg: error});
50 obj.instruction = sanitizeHtml(obj.instruction);
51 obj.solution = sanitizeHtml(obj.solution);
52 ProblemModel.update(obj, (err) => {
53 res.json(err || {});
54 });
55 });
56
57 router.delete("/problems", access.logged, access.ajax, (req,res) => {
58 const pid = req.query.id;
59 if (!pid.toString().match(/^[0-9]+$/))
60 res.json({errmsg: "Bad problem ID"});
61 ProblemModel.safeRemove(pid, req.userId, err => {
62 res.json(err || {});
63 });
64 });
65
66 module.exports = router;