Commit | Line | Data |
---|---|---|
89021f18 BA |
1 | var db = require("../utils/database"); |
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 | ||
14 | const ProblemModel = | |
15 | { | |
16 | checkProblem: function(p) | |
17 | { | |
18 | if (!p.vid.toString().match(/^[0-9]+$/)) | |
19 | return "Wrong variant ID"; | |
20 | if (!p.fen.match(/^[a-zA-Z0-9, /-]*$/)) | |
21 | return "Bad FEN string"; | |
22 | return ""; | |
23 | }, | |
24 | ||
25 | create: function(p, cb) | |
26 | { | |
27 | db.serialize(function() { | |
28 | const query = | |
29 | "INSERT INTO Problems " + | |
30 | "(added, uid, vid, fen, instruction, solution) " + | |
31 | "VALUES " + | |
32 | "(" + Date.now() + "," + p.uid + ",'" + p.fen + "',?,?)"; | |
33 | db.run(query, p.instruction, p.solution, function(err) { | |
34 | return cb(err, {pid: this.lastID}); | |
35 | }); | |
36 | }); | |
37 | }, | |
38 | ||
39 | getAll: function(cb) | |
40 | { | |
41 | db.serialize(function() { | |
42 | const query = | |
43 | "SELECT * " + | |
44 | "FROM Problems"; | |
45 | db.all(query, (err,problems) => { | |
46 | return cb(err, problems); | |
47 | }); | |
48 | }); | |
49 | }, | |
50 | ||
51 | getOne: function(id, cb) | |
52 | { | |
53 | db.serialize(function() { | |
54 | const query = | |
55 | "SELECT * " + | |
56 | "FROM Problems " + | |
57 | "WHERE id = " + id; | |
58 | db.get(query, (err,problem) => { | |
59 | return cb(err, problem); | |
60 | }); | |
61 | }); | |
62 | }, | |
63 | ||
64 | update: function(id, prob) | |
65 | { | |
66 | db.serialize(function() { | |
67 | let query = | |
68 | "UPDATE Problems " + | |
69 | "SET " + | |
70 | "vid = " + prob.vid + "," + | |
71 | "fen = " + prob.fen + "," + | |
72 | "instruction = " + prob.instruction + "," + | |
73 | "solution = " + prob.solution + " " + | |
74 | "WHERE id = " + id; | |
75 | db.run(query); | |
76 | }); | |
77 | }, | |
78 | ||
79 | remove: function(id) | |
80 | { | |
81 | db.serialize(function() { | |
82 | const query = | |
83 | "DELETE FROM Problems " + | |
84 | "WHERE id = " + id; | |
85 | db.run(query); | |
86 | }); | |
87 | }, | |
88 | ||
89 | safeRemove: function(id, uid, cb) | |
90 | { | |
91 | db.serialize(function() { | |
92 | const query = | |
93 | "SELECT 1 " + | |
94 | "FROM Problems " + | |
95 | "WHERE id = " + id + " AND uid = " + uid; | |
96 | db.get(query, (err,prob) => { | |
97 | if (!prob) | |
98 | return cb({errmsg: "Not your problem"}); | |
99 | ProvlemModel.remove(id); | |
100 | cb(null); | |
101 | }); | |
102 | }); | |
103 | }, | |
104 | } | |
105 | ||
106 | module.exports = ProblemModel; |