1 var db
= require("../utils/database");
4 * Structure table Challenges:
8 * vid: variant id (int)
10 * fen: varchar (optional)
14 * Structure table WillPlay:
15 * cid: ref challenge id
19 const ChallengeModel
=
21 checkChallenge: function(c
)
23 const vid
= parseInt(c
.vid
);
24 if (isNaN(vid
) || vid
<= 0)
25 return "Please select a variant";
27 const mainTime
= parseInt(c
.mainTime
);
28 const increment
= parseInt(c
.increment
);
29 if (isNaN(mainTime
) || mainTime
<= 0)
30 return "Main time should be strictly positive";
31 if (isNaN(increment
) || increment
< 0)
32 return "Increment must be positive";
34 // Basic alphanumeric check for players names
38 if (p
.name
.length
> 0)
40 if (!p
.name
.match(/^[\w]+$/))
41 return "Wrong characters in players names";
46 if (playerCount
> 0 && playerCount
!= c
.nbPlayers
-1)
47 return "None, or all of the opponent names must be filled"
49 // Just characters check on server:
50 if (!c
.fen
.match(/^[a-zA-Z0-9, /-]*$/))
51 return "Bad FEN string";
54 // fen cannot be undefined; TODO: generate fen on server instead
55 create: function(c
, cb
)
57 db
.serialize(function() {
59 "INSERT INTO Challenges " +
60 "(added, uid, vid, nbPlayers, fen, mainTime, addTime) VALUES " +
61 "(" + Date
.now() + "," + c
.uid
+ "," + c
.vid
+ "," + c
.nbPlayers
+
62 ",'" + c
.fen
+ "'," + c
.mainTime
+ "," + c
.increment
+ ")";
63 db
.run(query
, err
=> {
66 db
.get("SELECT last_insert_rowid() AS rowid", (err2
,lastId
) => {
68 "INSERT INTO WillPlay VALUES " +
69 "(" + lastId
["rowid"] + "," + c
.uid
+ ")";
70 db
.run(query
, (err
,ret
) => {
71 cb(err
, lastId
); //all we need is the challenge ID
78 getOne: function(id
, cb
)
80 db
.serialize(function() {
83 "FROM Challenges c " +
87 db
.get(query
, (err
,challengeInfo
) => {
91 "SELECT w.uid AS id, u.name " +
95 "WHERE w.cid = " + id
;
96 db
.run(query
, (err2
,players
) => {
101 uid: challengeInfo
.uid
,
102 vname: challengeInfo
.name
,
103 added: challengeInfo
.added
,
104 nbPlayers: challengeInfo
.nbPlayers
,
105 players: players
, //currently in
106 fen: challengeInfo
.fen
,
107 mainTime: challengeInfo
.mainTime
,
108 increment: challengeInfo
.addTime
,
110 return cb(null, challenge
);
116 getByUser: function(uid
, cb
)
118 db
.serialize(function() {
122 "WHERE uid = " + uid
;
123 db
.run(query
, (err
,challIds
) => {
127 challIds
.forEach(cidRow
=> {
128 ChallengeModel
.getOne(cidRow
["cid"], (err2
,chall
) => {
131 challenges
.push(chall
);
134 return cb(null, challenges
);
141 db
.parallelize(function() {
143 "DELETE FROM Challenges " +
147 "DELETE FROM WillPlay " +
154 module
.exports
= ChallengeModel
;