Draft of problems section
[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 || {pid:ret.pid});
42 });
43 });
44
45 router.put("/problems", access.logged, access.ajax, (req,res) => {
46 const pid = req.body.pid;
47 let error = "";
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);
54 if (!!error)
55 return res.json({errmsg: error});
56 ProblemModel.update(pid, obj, (err) => {
57 res.json(err || {});
58 });
59 });
60
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 => {
66 res.json(err || {});
67 });
68 });
69
70 module.exports = router;