Fixes
[vchess.git] / server / routes / problems.js
CommitLineData
89021f18
BA
1// AJAX methods to get, create, update or delete a problem
2
3let router = require("express").Router();
4const access = require("../utils/access");
5const ProblemModel = require("../models/Problem");
6const sanitizeHtml = require('sanitize-html');
7
8router.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
28router.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) => {
bd76b456 41 return res.json(err || {id:ret.pid});
89021f18
BA
42 });
43});
44
45router.put("/problems", access.logged, access.ajax, (req,res) => {
604b951e
BA
46 let obj = req.body.prob;
47 const error = ProblemModel.checkProblem(obj);
89021f18
BA
48 if (!!error)
49 return res.json({errmsg: error});
604b951e
BA
50 obj.instruction = sanitizeHtml(obj.instruction);
51 obj.solution = sanitizeHtml(obj.solution);
52 ProblemModel.update(obj, (err) => {
89021f18
BA
53 res.json(err || {});
54 });
55});
56
57router.delete("/problems", access.logged, access.ajax, (req,res) => {
58 const pid = req.query.id;
bd76b456 59 if (!pid.toString().match(/^[0-9]+$/))
89021f18
BA
60 res.json({errmsg: "Bad problem ID"});
61 ProblemModel.safeRemove(pid, req.userId, err => {
62 res.json(err || {});
63 });
64});
65
66module.exports = router;