Add roadmap on TODO file
[vchess.git] / routes / problems.js
... / ...
CommitLineData
1let router = require("express").Router();
2const sqlite3 = require('sqlite3');
3const DbPath = __dirname.replace("/routes", "/db/vchess.sqlite");
4const db = new sqlite3.Database(DbPath);
5const sanitizeHtml = require('sanitize-html');
6const MaxNbProblems = 20;
7
8// Fetch N previous or next problems (AJAX)
9router.get("/problems/:variant([a-zA-Z0-9]+)", (req,res) => {
10 if (!req.xhr)
11 return res.json({errmsg: "Unauthorized access"});
12 const vname = req.params["variant"];
13 const directionStr = (req.query.direction == "forward" ? ">" : "<");
14 const lastDt = req.query.last_dt;
15 if (!lastDt.match(/[0-9]+/))
16 return res.json({errmsg: "Bad timestamp"});
17 db.serialize(function() {
18 const query = "SELECT * FROM Problems " +
19 "WHERE variant='" + vname + "' " +
20 " AND added " + directionStr + " " + lastDt + " " +
21 "ORDER BY added " + (directionStr=="<" ? "DESC " : "") +
22 "LIMIT " + MaxNbProblems;
23 db.all(query, (err,problems) => {
24 if (!!err)
25 return res.json(err);
26 return res.json({problems: problems});
27 });
28 });
29});
30
31// Upload a problem (AJAX)
32router.post("/problems/:variant([a-zA-Z0-9]+)", (req,res) => {
33 if (!req.xhr)
34 return res.json({errmsg: "Unauthorized access"});
35 const vname = req.params["variant"];
36 const timestamp = Date.now();
37 // Sanitize them
38 const fen = req.body["fen"];
39 if (!fen.match(/^[a-zA-Z0-9, /-]*$/))
40 return res.json({errmsg: "Bad characters in FEN string"});
41 const instructions = sanitizeHtml(req.body["instructions"]).trim();
42 const solution = sanitizeHtml(req.body["solution"]).trim();
43 if (instructions.length == 0)
44 return res.json({errmsg: "Empty instructions"});
45 if (solution.length == 0)
46 return res.json({errmsg: "Empty solution"});
47 db.serialize(function() {
48 let stmt = db.prepare("INSERT INTO Problems " +
49 "(added,variant,fen,instructions,solution) VALUES (?,?,?,?,?)");
50 stmt.run(timestamp, vname, fen, instructions, solution);
51 stmt.finalize();
52 });
53 res.json({});
54});
55
56// TODO: edit, delete a problem
57
58module.exports = router;