1 let express
= require('express');
2 let router
= express
.Router();
3 const createError
= require('http-errors');
4 const sqlite3
= require('sqlite3');//.verbose();
5 const db
= new sqlite3
.Database('db/vchess.sqlite');
6 const sanitizeHtml
= require('sanitize-html');
9 router
.get('/', function(req
, res
, next
) {
10 db
.serialize(function() {
11 db
.all("SELECT * FROM Variants", (err
,variants
) => {
16 variantArray: variants
, //JSON.stringify(variants)
23 router
.get("/:vname([a-zA-Z0-9]+)", (req
,res
,next
) => {
24 const vname
= req
.params
["vname"];
25 db
.serialize(function() {
26 db
.all("SELECT * FROM Variants WHERE name='" + vname
+ "'", (err
,variant
) => {
29 if (!variant
|| variant
.length
==0)
30 return next(createError(404));
31 // TODO (later...) get only n=100(?) most recent problems
32 db
.all("SELECT * FROM Problems WHERE variant='" + vname
+ "'",
36 res
.render('variant', {
37 title: vname
+ ' Variant',
39 problemArray: problems
,
47 // Load a rules page (AJAX)
48 router
.get("/rules/:variant([a-zA-Z0-9]+)", (req
,res
) => {
50 return res
.json({errmsg: "Unauthorized access"});
51 res
.render("rules/" + req
.params
["variant"]);
54 // Fetch 10 previous or next problems (AJAX)
55 router
.get("/problems/:variant([a-zA-Z0-9]+)", (req
,res
) => {
57 return res
.json({errmsg: "Unauthorized access"});
58 // TODO: next or previous: in params + timedate (of current oldest or newest)
59 db
.serialize(function() {
64 // Upload a problem (AJAX)
65 router
.post("/problems/:variant([a-zA-Z0-9]+)", (req
,res
) => {
67 return res
.json({errmsg: "Unauthorized access"});
68 const vname
= req
.params
["variant"];
69 const timestamp
= Date
.now();
71 const fen
= req
.body
["fen"];
72 if (!fen
.match(/^[a-zA-Z0-9, /-]*$/))
73 return res
.json({errmsg: "Bad characters in FEN string"});
74 const instructions
= sanitizeHtml(req
.body
["instructions"]);
75 const solution
= sanitizeHtml(req
.body
["solution"]);
76 db
.serialize(function() {
77 let stmt
= db
.prepare("INSERT INTO Problems " +
78 "(added,variant,fen,instructions,solution) VALUES (?,?,?,?,?)");
79 stmt
.run(timestamp
, vname
, fen
, instructions
, solution
);
85 module
.exports
= router
;