Fix Koopa chess + select only required fields in userMode.getOne()
[vchess.git] / server / models / Challenge.js
1 const db = require("../utils/database");
2 const UserModel = require("./User");
3
4 /*
5 * Structure:
6 * id: integer
7 * added: datetime
8 * uid: user id (int)
9 * target: recipient id (optional)
10 * vid: variant id (int)
11 * randomness: integer in 0..2
12 * fen: varchar (optional)
13 * cadence: string (3m+2s, 7d ...)
14 */
15
16 const ChallengeModel = {
17 checkChallenge: function(c) {
18 return (
19 c.vid.toString().match(/^[0-9]+$/) &&
20 c.cadence.match(/^[0-9dhms +]+$/) &&
21 c.randomness.toString().match(/^[0-2]$/) &&
22 c.fen.match(/^[a-zA-Z0-9, /-]*$/) &&
23 (!c.to || UserModel.checkNameEmail({ name: c.to }))
24 );
25 },
26
27 create: function(c, cb) {
28 db.serialize(function() {
29 const query =
30 "INSERT INTO Challenges " +
31 "(added, uid, " + (c.to ? "target, " : "") +
32 "vid, randomness, fen, cadence) " +
33 "VALUES " +
34 "(" + Date.now() + "," + c.uid + "," + (c.to ? c.to + "," : "") +
35 c.vid + "," + c.randomness + ",'" + c.fen + "','" + c.cadence + "')";
36 db.run(query, function(err) {
37 cb(err, { id: this.lastID });
38 });
39 });
40 },
41
42 // All challenges related to user with ID uid
43 getByUser: function(uid, cb) {
44 db.serialize(function() {
45 const query =
46 "SELECT * " +
47 "FROM Challenges " +
48 "WHERE target IS NULL" +
49 " OR uid = " + uid +
50 " OR target = " + uid;
51 db.all(query, (err, challenges) => {
52 cb(err, challenges);
53 });
54 });
55 },
56
57 remove: function(id) {
58 db.serialize(function() {
59 const query =
60 "DELETE FROM Challenges " +
61 "WHERE id = " + id;
62 db.run(query);
63 });
64 },
65
66 safeRemove: function(id, uid) {
67 db.serialize(function() {
68 const query =
69 "SELECT 1 " +
70 "FROM Challenges " +
71 "WHERE id = " + id + " " +
72 // Condition: I'm the sender or the target
73 "AND (uid = " + uid + " OR target = " + uid + ")";
74 db.get(query, (err,chall) => {
75 if (!err && chall)
76 ChallengeModel.remove(id);
77 });
78 });
79 },
80 }
81
82 module.exports = ChallengeModel;