602531f4456c482d92112e3da2f107477c405af4
1 var db
= require("../utils/database");
8 * target: recipient id (optional)
9 * vid: variant id (int)
10 * fen: varchar (optional)
11 * timeControl: string (3m+2s, 7d+1d ...)
14 const ChallengeModel
=
16 checkChallenge: function(c
)
18 if (!c
.vid
.match(/^[0-9]+$/))
19 return "Wrong variant ID";
21 if (!c
.timeControl
.match(/^[0-9dhms
+]+$/))
22 return "Wrong characters in time control";
24 if (!c
.fen
.match(/^[a-zA-Z0-9, /-]+$/))
25 return "Bad FEN string";
28 // fen cannot be undefined
29 create: function(c
, cb
)
31 db
.serialize(function() {
33 "INSERT INTO Challenges " +
34 "(added, uid, " + (!!c
.to
? "target, " : "") +
35 "vid, fen, timeControl) VALUES " +
36 "(" + Date
.now() + "," + c
.uid
+ "," + (!!c
.to
? c
.to
+ "," : "") +
37 c
.vid
+ ",'" + c
.fen
+ "','" + c
.timeControl
+ "')";
38 db
.run(query
, err
=> {
41 db
.get("SELECT last_insert_rowid() AS rowid", (err2
,lastId
) => {
42 return cb(err2
, lastId
);
48 getOne: function(id
, cb
)
50 db
.serialize(function() {
55 db
.get(query
, (err
,challengeInfo
) => {
59 if (!!challengeInfo
.to
)
60 condition
= "IN (" + challengeInfo
.uid
+ "," + challengeInfo
.to
+ ")";
62 condition
= "= " + challengeInfo
.uid
;
66 "WHERE id " + condition
;
67 db
.run(query
, (err2
,players
) => {
72 uid: challengeInfo
.uid
, //sender (but we don't know who ask)
73 vid: challengeInfo
.vid
,
74 added: challengeInfo
.added
,
75 players: players
, //sender + potential receiver
76 fen: challengeInfo
.fen
,
77 timeControl: challengeInfo
.timeControl
,
79 return cb(null, challenge
);
85 getByUser: function(uid
, cb
)
87 db
.serialize(function() {
92 db
.run(query
, (err
,challIds
) => {
95 challIds
= challIds
|| [];
97 challIds
.forEach(cidRow
=> {
98 ChallengeModel
.getOne(cidRow
["cid"], (err2
,chall
) => {
101 challenges
.push(chall
);
104 return cb(null, challenges
);
109 remove: function(id
, uid
)
111 db
.serialize(function() {
115 "WHERE id = " + id
+ " AND uid = " + uid
;
116 db
.run(query
, (err
,rows
) => {
117 if (rows
.length
== 0)
118 return res
.json({errmsg: "Not your challenge"});
120 "DELETE FROM Challenges " +
128 module
.exports
= ChallengeModel
;