Update on challenges
[vchess.git] / server / models / Challenge.js
CommitLineData
8d7e2786
BA
1var db = require("../utils/database");
2
3/*
bf20f404 4 * Structure:
00f2759e
BA
5 * id: integer
6 * added: datetime
7 * uid: user id (int)
bf20f404 8 * target: recipient id (optional)
00f2759e 9 * vid: variant id (int)
ab4f4bf2 10 * fen: varchar (optional)
052d17ea 11 * timeControl: string (3m+2s, 7d+1d ...)
8d7e2786
BA
12 */
13
ab4f4bf2 14const ChallengeModel =
8d7e2786 15{
b1aa927b
BA
16 checkChallenge: function(c)
17 {
052d17ea 18 if (!c.vid.match(/^[0-9]+$/))
b1aa927b 19 return "Wrong variant ID";
98db2082 20
052d17ea
BA
21 if (!c.timeControl.match(/^[0-9dhms +]+$/))
22 return "Wrong characters in time control";
98db2082 23
b1aa927b
BA
24 if (!c.fen.match(/^[a-zA-Z0-9, /-]+$/))
25 return "Bad FEN string";
26 },
98db2082 27
b1aa927b
BA
28 // fen cannot be undefined
29 create: function(c, cb)
30 {
31 db.serialize(function() {
32 let query =
33 "INSERT INTO Challenges " +
34 "(added, uid, " + (!!c.to ? "target, " : "") +
bf20f404 35 "vid, fen, timeControl) VALUES " +
b1aa927b 36 "(" + Date.now() + "," + c.uid + "," + (!!c.to ? c.to + "," : "") +
bf20f404 37 c.vid + ",'" + c.fen + "','" + c.timeControl + "')";
b1aa927b
BA
38 db.run(query, err => {
39 return cb(err);
bf20f404 40 });
b1aa927b
BA
41 });
42 },
ab4f4bf2 43
b1aa927b
BA
44 getOne: function(id, cb)
45 {
46 db.serialize(function() {
47 let query =
48 "SELECT * " +
49 "FROM Challenges " +
50 "WHERE id = " + id;
51 db.get(query, (err,challenge) => {
52 return cb(err, challenge);
53 });
54 });
55 },
8d7e2786 56
b1aa927b
BA
57 // all challenges except where target is defined and not me
58 getByUser: function(uid, cb)
59 {
60 db.serialize(function() {
61 const query =
62 "SELECT * " +
63 "FROM Challenges " +
64 "WHERE target IS NULL OR target = " + uid;
65 db.run(query, (err,challenges) => {
66 return cb(err, challenges);
67 });
68 });
69 },
8d7e2786 70
b1aa927b
BA
71 remove: function(id, uid)
72 {
73 db.serialize(function() {
74 let query =
4edfed6c
BA
75 "SELECT 1 " +
76 "FROM Challenges " +
77 "WHERE id = " + id + " AND uid = " + uid;
78 db.run(query, (err,rows) => {
bf20f404
BA
79 if (rows.length == 0)
80 return res.json({errmsg: "Not your challenge"});
81 query =
82 "DELETE FROM Challenges " +
83 "WHERE id = " + id;
84 db.run(query);
36093eba 85 });
b1aa927b
BA
86 });
87 },
8d7e2786 88}
ab4f4bf2
BA
89
90module.exports = ChallengeModel;