Draft Game and Challenge models
[vchess.git] / models / Challenge.js
CommitLineData
8d7e2786
BA
1var db = require("../utils/database");
2
3/*
00f2759e
BA
4 * Structure table Challenges:
5 * id: integer
6 * added: datetime
7 * uid: user id (int)
8 * vid: variant id (int)
9 * nbPlayers: integer
10 *
11 * Structure table WillPlay:
12 * cid: ref challenge id
13 * uid: ref user id
8d7e2786
BA
14 */
15
00f2759e 16exports.create = function(uid, vid, nbPlayers, cb)
8d7e2786 17{
00f2759e
BA
18 db.serialize({
19 let query =
20 "INSERT INTO Challenges (added, uid, vid, nbPlayers) " +
21 "VALUES (" + Date.now() + "," + uid + "," + vid + "," + nbPlayers + ")";
22 db.run(insertQuery, err => {
23 if (!!err)
24 return cb(err);
25 db.get("SELECT last_insert_rowid() AS rowid", (err2,lastId) => {
26 query =
27 "INSERT INTO WillPlay VALUES " +
28 "(" + lastId["rowid"] + "," + uid + ")";
29 db.run(query, cb);
30 });
31 });
32 });
33 });
8d7e2786
BA
34}
35
00f2759e 36exports.getOne = function(id, cb)
8d7e2786 37{
00f2759e
BA
38 db.serialize(function() {
39 let query =
40 "SELECT * " +
41 "FROM Challenges c " +
42 "JOIN Variants v " +
43 " ON c.vid = v.id "
44 "WHERE id = " + id;
45 db.get(query, (err,challengeInfo) => {
46 if (!!err)
47 return cb(err);
48 query =
49 "SELECT w.uid AS id, u.name " +
50 "FROM WillPlay w " +
51 "JOIN Users u " +
52 " ON w.uid = u.id " +
53 "WHERE w.cid = " + id;
54 db.run(query, (err2,players) => {
55 if (!!err2)
56 return cb(err2);
57 const challenge = {
58 id: id,
59 vname: challengeInfo.name,
60 added: challengeInfo.added,
61 nbPlayers: challengeInfo.nbPlayers,
62 players: players, //currently in
63 };
64 return cb(null, challenge);
65 });
66 });
67 });
8d7e2786
BA
68}
69
00f2759e 70exports.remove = function(id)
8d7e2786 71{
00f2759e
BA
72 db.parallelize(function() {
73 let query =
74 "DELETE FROM Challenges " +
75 "WHERE id = " + id;
76 db.run(query);
77 query =
78 "DELETE FROM WillPlay " +
79 "WHERE cid = " + id;
80 db.run(query);
8d7e2786
BA
81 });
82}