02088357c30a0bfc637141cffd6749f0e792f5ef
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
|| {id:ret
.pid
});
45 router
.put("/problems", access
.logged
, access
.ajax
, (req
,res
) => {
46 let obj
= req
.body
.prob
;
47 const error
= ProblemModel
.checkProblem(obj
);
49 return res
.json({errmsg: error
});
50 obj
.instruction
= sanitizeHtml(obj
.instruction
);
51 obj
.solution
= sanitizeHtml(obj
.solution
);
52 ProblemModel
.update(obj
, (err
) => {
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
=> {
66 module
.exports
= router
;