96db0a2b431ad5237d8b08b4bcfceca3c4155212
[vchess.git] / models / Challenge.js
1 var db = require("../utils/database");
2
3 /*
4 * Structure table Challenges:
5 * id: integer
6 * added: datetime
7 * uid: user id (int)
8 * vid: variant id (int)
9 * nbPlayers: integer
10 * fen: varchar (optional)
11 * mainTime: integer
12 * addTime: integer
13 *
14 * Structure table WillPlay:
15 * cid: ref challenge id
16 * uid: ref user id
17 */
18
19 const ChallengeModel =
20 {
21 // fen cannot be undefined; TODO: generate fen on server instead
22 create: function(c, cb)
23 {
24 db.serialize(function() {
25 let query =
26 "INSERT INTO Challenges " +
27 "(added, uid, vid, nbPlayers, fen, mainTime, addTime) VALUES " +
28 "(" + Date.now() + "," + c.uid + "," + c.vid + "," + c.nbPlayers +
29 ",'" + c.fen + "'," + c.mainTime + "," + c.increment + ")";
30 db.run(query, err => {
31 if (!!err)
32 return cb(err);
33 db.get("SELECT last_insert_rowid() AS rowid", (err2,lastId) => {
34 query =
35 "INSERT INTO WillPlay VALUES " +
36 "(" + lastId["rowid"] + "," + c.uid + ")";
37 db.run(query, (err,ret) => {
38 cb(err, lastId); //all we need is the challenge ID
39 });
40 });
41 });
42 });
43 },
44
45 getOne: function(id, cb)
46 {
47 db.serialize(function() {
48 let query =
49 "SELECT * " +
50 "FROM Challenges c " +
51 "JOIN Variants v " +
52 " ON c.vid = v.id "
53 "WHERE id = " + id;
54 db.get(query, (err,challengeInfo) => {
55 if (!!err)
56 return cb(err);
57 query =
58 "SELECT w.uid AS id, u.name " +
59 "FROM WillPlay w " +
60 "JOIN Users u " +
61 " ON w.uid = u.id " +
62 "WHERE w.cid = " + id;
63 db.run(query, (err2,players) => {
64 if (!!err2)
65 return cb(err2);
66 const challenge = {
67 id: id,
68 uid: challengeInfo.uid,
69 vname: challengeInfo.name,
70 added: challengeInfo.added,
71 nbPlayers: challengeInfo.nbPlayers,
72 players: players, //currently in
73 fen: challengeInfo.fen,
74 mainTime: challengeInfo.mainTime,
75 increment: challengeInfo.addTime,
76 };
77 return cb(null, challenge);
78 });
79 });
80 });
81 },
82
83 getByUser: function(uid, cb)
84 {
85 db.serialize(function() {
86 const query =
87 "SELECT cid " +
88 "FROM WillPlay " +
89 "WHERE uid = " + uid;
90 db.run(query, (err,challIds) => {
91 if (!!err)
92 return cb(err);
93 let challenges = [];
94 challIds.forEach(cidRow => {
95 ChallengeModel.getOne(cidRow["cid"], (err2,chall) => {
96 if (!!err2)
97 return cb(err2);
98 challenges.push(chall);
99 });
100 });
101 return cb(null, challenges);
102 });
103 });
104 },
105
106 remove: function(id)
107 {
108 db.parallelize(function() {
109 let query =
110 "DELETE FROM Challenges " +
111 "WHERE id = " + id;
112 db.run(query);
113 query =
114 "DELETE FROM WillPlay " +
115 "WHERE cid = " + id;
116 db.run(query);
117 });
118 },
119 }
120
121 module.exports = ChallengeModel;