Update installation instructions
[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 14const ProblemModel = {
937c24ab 15
0234201f 16 checkProblem: function(p) {
866842c3
BA
17 return (
18 p.id.toString().match(/^[0-9]+$/) &&
19 p.vid.toString().match(/^[0-9]+$/) &&
20 p.fen.match(/^[a-zA-Z0-9, /-]*$/)
21 );
89021f18
BA
22 },
23
0234201f 24 create: function(p, cb) {
89021f18
BA
25 db.serialize(function() {
26 const query =
27 "INSERT INTO Problems " +
28 "(added, uid, vid, fen, instruction, solution) " +
29 "VALUES " +
604b951e
BA
30 "(" + Date.now() + "," + p.uid + "," + p.vid + ",'" + p.fen + "',?,?)";
31 db.run(query, [p.instruction,p.solution], function(err) {
0234201f 32 cb(err, { id: this.lastID });
89021f18
BA
33 });
34 });
35 },
36
84fc0f02
BA
37 getNext: function(uid, onlyMine, cursor, cb) {
38 let condition = "";
39 if (onlyMine) condition = "AND uid = " + uid + " ";
40 else if (!!uid) condition = "AND uid <> " + uid + " ";
89021f18
BA
41 db.serialize(function() {
42 const query =
43 "SELECT * " +
68e19a44
BA
44 "FROM Problems " +
45 "WHERE added < " + cursor + " " +
84fc0f02 46 condition +
68e19a44
BA
47 "ORDER BY added DESC " +
48 "LIMIT 20"; //TODO: 20 is arbitrary
49 db.all(query, (err, problems) => {
866842c3 50 cb(err, problems);
89021f18
BA
51 });
52 });
53 },
54
0234201f 55 getOne: function(id, cb) {
89021f18
BA
56 db.serialize(function() {
57 const query =
58 "SELECT * " +
59 "FROM Problems " +
60 "WHERE id = " + id;
68e19a44 61 db.get(query, (err, problem) => {
866842c3 62 cb(err, problem);
89021f18
BA
63 });
64 });
65 },
66
a9e79351 67 safeUpdate: function(prob, uid, devs) {
89021f18 68 db.serialize(function() {
a9e79351
BA
69 let whereClause = "WHERE id = " + prob.id;
70 if (!devs.includes(uid)) whereClause += " AND uid = " + uid;
866842c3 71 const query =
89021f18
BA
72 "UPDATE Problems " +
73 "SET " +
74 "vid = " + prob.vid + "," +
604b951e
BA
75 "fen = '" + prob.fen + "'," +
76 "instruction = ?," +
77 "solution = ? " +
a9e79351 78 whereClause;
68e19a44 79 db.run(query, [prob.instruction, prob.solution]);
89021f18
BA
80 });
81 },
82
a9e79351 83 safeRemove: function(id, uid, devs) {
89021f18 84 db.serialize(function() {
0705a80c 85 let whereClause = "WHERE id = " + id;
a9e79351 86 if (!devs.includes(uid)) whereClause += " AND uid = " + uid;
89021f18
BA
87 const query =
88 "DELETE FROM Problems " +
a9e79351 89 whereClause;
866842c3 90 db.run(query);
89021f18 91 });
937c24ab
BA
92 }
93
94};
89021f18
BA
95
96module.exports = ProblemModel;