1 const db
= require("../utils/database");
2 const UserModel
= require("./User");
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 ...)
16 const ChallengeModel
=
18 checkChallenge: function(c
)
21 c
.vid
.toString().match(/^[0-9]+$/) &&
22 c
.cadence
.match(/^[0-9dhms
+]+$/) &&
23 c
.randomness
.toString().match(/^[0-2]$/) &&
24 c
.fen
.match(/^[a-zA-Z0-9, /-]*$/) &&
25 (!c
.to
|| UserModel
.checkNameEmail({name: c
.to
}))
29 create: function(c
, cb
)
31 db
.serialize(function() {
33 "INSERT INTO Challenges " +
34 "(added, uid, " + (c
.to
? "target, " : "") +
35 "vid, randomness, fen, cadence) " +
37 "(" + Date
.now() + "," + c
.uid
+ "," + (c
.to
? c
.to
+ "," : "") +
38 c
.vid
+ "," + c
.randomness
+ ",'" + c
.fen
+ "','" + c
.cadence
+ "')";
39 db
.run(query
, function(err
) {
40 cb(err
, {cid: this.lastID
});
45 // All challenges related to user with ID uid
46 getByUser: function(uid
, cb
)
48 db
.serialize(function() {
52 "WHERE target IS NULL" +
54 " OR target = " + uid
;
55 db
.all(query
, (err
,challenges
) => {
63 db
.serialize(function() {
65 "DELETE FROM Challenges " +
71 safeRemove: function(id
, uid
)
73 db
.serialize(function() {
77 "WHERE id = " + id
+ " " +
78 // Condition: I'm the sender or the target
79 "AND (uid = " + uid
+ " OR target = " + uid
+ ")";
80 db
.get(query
, (err
,chall
) => {
82 ChallengeModel
.remove(id
);
88 module
.exports
= ChallengeModel
;