1 // AJAX methods to get, create, update or delete a problem
3 let router
= require("express").Router();
4 const access
= require("../utils/access");
5 const ProblemModel
= require("../models/Problem");
6 const sanitizeHtml
= require('sanitize-html');
8 router
.get("/problems", (req
,res
) => {
9 const probId
= req
.query
["pid"];
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
});
22 ProblemModel
.getAll((err
,problems
) => {
23 res
.json(err
|| {problems:problems
});
28 router
.post("/problems", access
.logged
, access
.ajax
, (req
,res
) => {
29 const error
= ProblemModel
.checkProblem(req
.body
.prob
);
31 return res
.json({errmsg:error
});
34 vid: req
.body
.prob
.vid
,
35 fen: req
.body
.prob
.fen
,
37 instruction: sanitizeHtml(req
.body
.prob
.instruction
),
38 solution: sanitizeHtml(req
.body
.prob
.solution
),
40 ProblemModel
.create(problem
, (err
,ret
) => {
41 return res
.json(err
|| {pid:ret
.pid
});
45 router
.put("/problems", access
.logged
, access
.ajax
, (req
,res
) => {
46 const pid
= req
.body
.pid
;
48 if (!pid
.toString().match(/^[0-9]+$/))
49 error
= "Wrong problem ID";
50 let obj
= req
.body
.newProb
;
51 error
= ProblemModel
.checkProblem(obj
);
52 obj
.instruction
= sanitizeHtml(obj
.instruction
);
53 obj
.solution
= sanitizeHtml(obj
.solution
);
55 return res
.json({errmsg: error
});
56 ProblemModel
.update(pid
, obj
, (err
) => {
61 router
.delete("/problems", access
.logged
, access
.ajax
, (req
,res
) => {
62 const pid
= req
.query
.id
;
63 if (!pid
.match(/^[0-9]+$/))
64 res
.json({errmsg: "Bad problem ID"});
65 ProblemModel
.safeRemove(pid
, req
.userId
, err
=> {
70 module
.exports
= router
;