Add Knightrelay1. Some fixes. Move odd 'isAttackedBy_multiple_colors' to Checkered...
[vchess.git] / server / models / Problem.js
CommitLineData
c5c47010 1const db = require("../utils/database");
89021f18
BA
2
3/*
4 * Structure:
5 * id: integer
6 * added: datetime
7 * uid: user id (int)
8 * vid: variant id (int)
9 * fen: varchar (optional)
10 * instruction: text
11 * solution: text
12 */
13
0234201f
BA
14const ProblemModel = {
15 checkProblem: function(p) {
866842c3
BA
16 return (
17 p.id.toString().match(/^[0-9]+$/) &&
18 p.vid.toString().match(/^[0-9]+$/) &&
19 p.fen.match(/^[a-zA-Z0-9, /-]*$/)
20 );
89021f18
BA
21 },
22
0234201f 23 create: function(p, cb) {
89021f18
BA
24 db.serialize(function() {
25 const query =
26 "INSERT INTO Problems " +
27 "(added, uid, vid, fen, instruction, solution) " +
28 "VALUES " +
604b951e
BA
29 "(" + Date.now() + "," + p.uid + "," + p.vid + ",'" + p.fen + "',?,?)";
30 db.run(query, [p.instruction,p.solution], function(err) {
0234201f 31 cb(err, { id: this.lastID });
89021f18
BA
32 });
33 });
34 },
35
68e19a44 36 getNext: function(cursor, cb) {
89021f18
BA
37 db.serialize(function() {
38 const query =
39 "SELECT * " +
68e19a44
BA
40 "FROM Problems " +
41 "WHERE added < " + cursor + " " +
42 "ORDER BY added DESC " +
43 "LIMIT 20"; //TODO: 20 is arbitrary
44 db.all(query, (err, problems) => {
866842c3 45 cb(err, problems);
89021f18
BA
46 });
47 });
48 },
49
0234201f 50 getOne: function(id, cb) {
89021f18
BA
51 db.serialize(function() {
52 const query =
53 "SELECT * " +
54 "FROM Problems " +
55 "WHERE id = " + id;
68e19a44 56 db.get(query, (err, problem) => {
866842c3 57 cb(err, problem);
89021f18
BA
58 });
59 });
60 },
61
0234201f 62 safeUpdate: function(prob, uid) {
89021f18 63 db.serialize(function() {
866842c3 64 const query =
89021f18
BA
65 "UPDATE Problems " +
66 "SET " +
67 "vid = " + prob.vid + "," +
604b951e
BA
68 "fen = '" + prob.fen + "'," +
69 "instruction = ?," +
70 "solution = ? " +
866842c3 71 "WHERE id = " + prob.id + " AND uid = " + uid;
68e19a44 72 db.run(query, [prob.instruction, prob.solution]);
89021f18
BA
73 });
74 },
75
0234201f 76 safeRemove: function(id, uid) {
89021f18
BA
77 db.serialize(function() {
78 const query =
79 "DELETE FROM Problems " +
89021f18 80 "WHERE id = " + id + " AND uid = " + uid;
866842c3 81 db.run(query);
89021f18
BA
82 });
83 },
84}
85
86module.exports = ProblemModel;