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