62a2da15790ecb294cac37995f05a0bee65ebc70
1 let router
= require("express").Router();
2 const sqlite3
= require('sqlite3');
3 const DbPath
= __dirname
.replace("/routes", "/db/vchess.sqlite");
4 const db
= new sqlite3
.Database(DbPath
);
5 const sanitizeHtml
= require('sanitize-html');
6 const MaxNbProblems
= 20;
8 // Fetch N previous or next problems (AJAX)
9 router
.get("/problems/:variant([a-zA-Z0-9]+)", (req
,res
) => {
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
) => {
26 return res
.json({problems: problems
});
31 // Upload a problem (AJAX)
32 router
.post("/problems/:variant([a-zA-Z0-9]+)", (req
,res
) => {
34 return res
.json({errmsg: "Unauthorized access"});
35 const vname
= req
.params
["variant"];
36 const timestamp
= Date
.now();
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
);
56 // TODO: edit, delete a problem
58 module
.exports
= router
;