| 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 | checkProblem: function(p) { |
| 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 | ); |
| 21 | }, |
| 22 | |
| 23 | create: function(p, cb) { |
| 24 | db.serialize(function() { |
| 25 | const query = |
| 26 | "INSERT INTO Problems " + |
| 27 | "(added, uid, vid, fen, instruction, solution) " + |
| 28 | "VALUES " + |
| 29 | "(" + Date.now() + "," + p.uid + "," + p.vid + ",'" + p.fen + "',?,?)"; |
| 30 | db.run(query, [p.instruction,p.solution], function(err) { |
| 31 | cb(err, { id: this.lastID }); |
| 32 | }); |
| 33 | }); |
| 34 | }, |
| 35 | |
| 36 | getAll: function(cb) { |
| 37 | db.serialize(function() { |
| 38 | const query = |
| 39 | "SELECT * " + |
| 40 | "FROM Problems"; |
| 41 | db.all(query, (err,problems) => { |
| 42 | cb(err, problems); |
| 43 | }); |
| 44 | }); |
| 45 | }, |
| 46 | |
| 47 | getOne: function(id, cb) { |
| 48 | db.serialize(function() { |
| 49 | const query = |
| 50 | "SELECT * " + |
| 51 | "FROM Problems " + |
| 52 | "WHERE id = " + id; |
| 53 | db.get(query, (err,problem) => { |
| 54 | cb(err, problem); |
| 55 | }); |
| 56 | }); |
| 57 | }, |
| 58 | |
| 59 | safeUpdate: function(prob, uid) { |
| 60 | db.serialize(function() { |
| 61 | const query = |
| 62 | "UPDATE Problems " + |
| 63 | "SET " + |
| 64 | "vid = " + prob.vid + "," + |
| 65 | "fen = '" + prob.fen + "'," + |
| 66 | "instruction = ?," + |
| 67 | "solution = ? " + |
| 68 | "WHERE id = " + prob.id + " AND uid = " + uid; |
| 69 | db.run(query, [prob.instruction,prob.solution]); |
| 70 | }); |
| 71 | }, |
| 72 | |
| 73 | safeRemove: function(id, uid) { |
| 74 | db.serialize(function() { |
| 75 | const query = |
| 76 | "DELETE FROM Problems " + |
| 77 | "WHERE id = " + id + " AND uid = " + uid; |
| 78 | db.run(query); |
| 79 | }); |
| 80 | }, |
| 81 | } |
| 82 | |
| 83 | module.exports = ProblemModel; |