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
= {
17 checkChallenge: function(c
) {
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
}))
27 create: function(c
, cb
) {
28 db
.serialize(function() {
30 "INSERT INTO Challenges " +
31 "(added, uid, " + (c
.to
? "target, " : "") +
32 "vid, randomness, fen, cadence) " +
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
});
42 // All challenges related to user with ID uid
43 getByUser: function(uid
, cb
) {
44 db
.serialize(function() {
48 "WHERE target IS NULL" +
50 " OR target = " + uid
;
51 db
.all(query
, (err
, challenges
) => {
57 remove: function(id
) {
58 db
.serialize(function() {
60 "DELETE FROM Challenges " +
66 safeRemove: function(id
, uid
) {
67 db
.serialize(function() {
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
) => {
76 ChallengeModel
.remove(id
);
82 module
.exports
= ChallengeModel
;