Remove debug trace
[vchess.git] / routes / all.js
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');
7
8 // Home
9 router.get('/', function(req, res, next) {
10 db.serialize(function() {
11 db.all("SELECT * FROM Variants", (err,variants) => {
12 if (!!err)
13 return next(err);
14 res.render('index', {
15 title: 'club',
16 variantArray: variants, //JSON.stringify(variants)
17 });
18 });
19 });
20 });
21
22 // Variant
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) => {
27 if (!!err)
28 return next(err);
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 + "'",
33 (err2,problems) => {
34 if (!!err2)
35 return next(err2);
36 res.render('variant', {
37 title: vname + ' Variant',
38 variant: vname,
39 problemArray: problems,
40 });
41 }
42 );
43 });
44 });
45 });
46
47 // Load a rules page (AJAX)
48 router.get("/rules/:variant([a-zA-Z0-9]+)", (req,res) => {
49 if (!req.xhr)
50 return res.json({errmsg: "Unauthorized access"});
51 res.render("rules/" + req.params["variant"]);
52 });
53
54 // Fetch 10 previous or next problems (AJAX)
55 router.get("/problems/:variant([a-zA-Z0-9]+)", (req,res) => {
56 if (!req.xhr)
57 return res.json({errmsg: "Unauthorized access"});
58 // TODO: next or previous: in params + timedate (of current oldest or newest)
59 db.serialize(function() {
60 //TODO
61 });
62 });
63
64 // Upload a problem (AJAX)
65 router.post("/problems/:variant([a-zA-Z0-9]+)", (req,res) => {
66 if (!req.xhr)
67 return res.json({errmsg: "Unauthorized access"});
68 const vname = req.params["variant"];
69 const timestamp = Date.now();
70 // Sanitize them
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);
80 stmt.finalize();
81 });
82 res.json({});
83 });
84
85 module.exports = router;