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
) {
20 c
.vid
.toString().match(/^[0-9]+$/) &&
21 c
.cadence
.match(/^[0-9dhms
+]+$/) &&
22 c
.randomness
.toString().match(/^[0-2]$/) &&
23 c
.fen
.match(/^[a-zA-Z0-9, /-]*$/) &&
24 (!c
.to
|| UserModel
.checkNameEmail({ name: c
.to
}))
28 create: function(c
, cb
) {
29 db
.serialize(function() {
31 "INSERT INTO Challenges " +
32 "(added, uid, " + (c
.to
? "target, " : "") +
33 "vid, randomness, fen, cadence) " +
35 "(" + Date
.now() + "," + c
.uid
+ "," + (c
.to
? c
.to
+ "," : "") +
36 c
.vid
+ "," + c
.randomness
+ ",'" + c
.fen
+ "','" + c
.cadence
+ "')";
37 db
.run(query
, function(err
) {
38 cb(err
, { id: this.lastID
});
43 // All challenges related to user with ID uid
44 getByUser: function(uid
, cb
) {
45 db
.serialize(function() {
49 "WHERE target IS NULL" +
51 " OR target = " + uid
;
52 db
.all(query
, (err
, challenges
) => {
58 remove: function(id
) {
59 db
.serialize(function() {
61 "DELETE FROM Challenges " +
67 safeRemove: function(id
, uid
) {
68 db
.serialize(function() {
72 "WHERE id = " + id
+ " " +
73 // Condition: I'm the sender or the target
74 "AND (uid = " + uid
+ " OR target = " + uid
+ ")";
75 db
.get(query
, (err
,chall
) => {
77 ChallengeModel
.remove(id
);
84 module
.exports
= ChallengeModel
;