Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Seed and admin theo #6

Merged
merged 16 commits into from
Jan 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 4 additions & 6 deletions backend/database/schema.sql
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ CREATE TABLE
bio VARCHAR(350),
avatar VARCHAR(255),
alt VARCHAR(100),
player_id_ref INT NOT NULL,
FOREIGN KEY (player_id_ref) REFERENCES player(id)
player_id INT NOT NULL,
FOREIGN KEY (player_id) REFERENCES player(id)
);

CREATE TABLE
Expand All @@ -41,8 +41,6 @@ CREATE TABLE
start_time TIMESTAMP,
end_time TIMESTAMP,
is_won BOOLEAN,
player_id_ref INT NOT NULL,
game_id_ref INT NOT NULL,
FOREIGN KEY (player_id_ref) REFERENCES player(id),
FOREIGN KEY (game_id_ref) REFERENCES game(id)
FOREIGN KEY (player_id) REFERENCES player(id),
FOREIGN KEY (game_id) REFERENCES game(id)
);
69 changes: 68 additions & 1 deletion backend/seed.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ const seed = async () => {
);
}

for (let i = 0; i < 5; i += 1) {
for (let i = 0; i <= 15; i += 1) {
queries.push(
database.query(
"insert into player(role_id,username, email, password) values (?,?,?,?)",
Expand All @@ -45,6 +45,73 @@ const seed = async () => {
)
);
}
for (let i = 0; i < 1; i += 1) {
queries.push(
database.query(
"insert into game(name,alt,description,image) values (?,?,?,?)",
[
"tic-tac-toe",
"tic-tac-toe",
"Deux joueurs posent tour à tour un rond, pour l'un, une croix, pour l'autre, dans une grille de 3 cases par 3. Le but du jeu est d'obtenir un alignement (en ligne, colonne ou diagonale) de ses trois signes.",
faker.image.urlLoremFlickr(),
]
)
);
}
for (let i = 0; i < 1; i += 1) {
queries.push(
database.query(
"insert into game(name,alt,description,image) values (?,?,?,?)",
[
"memory",
"memory",
"Tout d'abord, il faut mélanger les cartes. Puis, les étaler face contre table afin qu'aucun des joueurs ne puissent les identifier. Une fois cela fait, le premier joueur retourne 2 cartes de son choix. Si les cartes sont identiques, le joueur les conserve à côté de lui et rejoue.",
faker.image.urlLoremFlickr(),
]
)
);
}
for (let i = 0; i < 1; i += 1) {
queries.push(
database.query(
"insert into game(name,alt,description,image) values (?,?,?,?)",

[
"typeracer",
"typeracer",
"TypeRacer est un jeu qui vous aide à améliorer vos compétences en matière de dactylographie. Il vous met en concurrence avec d'autres dactylos dans une course. Mais au lieu de manœuvrer une voiture ou un avatar sur une piste ou dans un labyrinthe, vous devrez taper des mots pour amener votre voiture du point A au point B. Ainsi, non seulement vous vous entraînerez à taper rapidement et avec précision, mais vous aurez aussi le plaisir de le faire.",
faker.image.urlLoremFlickr(),
]
)
);
}

for (let i = 0; i <= 10; i += 1) {
const startDate = faker.date.past({ years: 1 });
const d = new Date(startDate);
queries.push(
database.query(
"insert into party(player_id,game_id,start_time,end_time,is_won) values (?,?,?,?,?)",
[
Math.ceil(Math.random() * 16),
Math.ceil(Math.random() * 3),
startDate,
new Date(d.getTime() + Math.ceil(Math.random() * 45 * 60000)),
Math.floor(Math.random() * 2),
]
)
);
}
for (let i = 0; i <= 10; i += 1) {
const userId = i + 1;
const test = `${faker.lorem.words(1)} profilwe avatar`;
queries.push(
database.query(
"insert into profile(bio,avatar,alt,player_id) values (?,?,?,?)",
[faker.lorem.paragraph(), faker.image.avatar(), test, userId]
)
);
}

// requete
// "insert into player(role_id,username, email, password) values (?,?,?,?)",
Expand Down
32 changes: 32 additions & 0 deletions backend/src/controllers/partyControllers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// Import access to database tables
const tables = require("../tables");
const { transformTimeToMinute } = require("../services/time");

const browse = async (req, res, next) => {
try {
let party = [];
if (req.query.stat === "played") {
party = await tables.party.statByParty();
} else if (req.query.stat === "is_won") {
const stat = await tables.party.statByGame();
party.push(
{ name: "won", value: +stat[0].victory },
{ name: "lost", value: +stat[0].defeat }
);
} else if (req.query.stat === "timeperplayer") {
const stat = await tables.party.timeperplayer();
party = stat.map((el) => ({
name: el.username,
value: transformTimeToMinute(el.time),
}));
} else {
party = await tables.party.readAll();
}
res.status(200).json(party);
} catch (err) {
next(err);
}
};
module.exports = {
browse,
};
26 changes: 0 additions & 26 deletions backend/src/models/ItemManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,58 +2,32 @@ const AbstractManager = require("./AbstractManager");

class ItemManager extends AbstractManager {
constructor() {
// Call the constructor of the parent class (AbstractManager)
// and pass the table name "item" as configuration
super({ table: "item" });
}

// The C of CRUD - Create operation

async create(item) {
// Execute the SQL INSERT query to add a new item to the "item" table
const [result] = await this.database.query(
`insert into ${this.table} (title) values (?)`,
[item.title]
);

// Return the ID of the newly inserted item
return result.insertId;
}

// The Rs of CRUD - Read operations

async read(id) {
// Execute the SQL SELECT query to retrieve a specific item by its ID
const [rows] = await this.database.query(
`select * from ${this.table} where id = ?`,
[id]
);

// Return the first row of the result, which represents the item
return rows[0];
}

async readAll() {
// Execute the SQL SELECT query to retrieve all items from the "item" table
const [rows] = await this.database.query(`select * from ${this.table}`);

// Return the array of items
return rows;
}

// The U of CRUD - Update operation
// TODO: Implement the update operation to modify an existing item

// async update(item) {
// ...
// }

// The D of CRUD - Delete operation
// TODO: Implement the delete operation to remove an item by its ID

// async delete(id) {
// ...
// }
}

module.exports = ItemManager;
42 changes: 42 additions & 0 deletions backend/src/models/PartyManager.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
const AbstractManager = require("./AbstractManager");

class PartyManager extends AbstractManager {
constructor() {
super({ table: "party" });
}

async readAll() {
const [rows] = await this.database.query(`select * from ${this.table}`);
return rows;
}

async statByParty() {
const [rows] = await this.database.query(
`select count(party.game_id) as value , g.name from ${this.table} inner join game as g on g.id = ${this.table}.game_id group by g.name`
);
return rows;
}

async statByGame() {
const [rows] = await this.database.query(`
select
sum(case when is_won = 1 then 1 else 0 end) as victory,
sum(case when is_won = 0 then 1 else 0 end) as defeat
from ${this.table}
`);
return rows;
}

async timePerPlayer() {
const [rows] = await this.database.query(`
SELECT p.player_id, pl.username, SEC_TO_TIME(SUM(TIME_TO_SEC(TIMEDIFF(p.end_time, p.start_time)))) AS time
FROM party p
JOIN player pl ON p.player_id = pl.id
GROUP BY p.player_id, pl.username
ORDER BY TIME_TO_SEC(time) DESC;
`);
return rows;
}
}

module.exports = PartyManager;
2 changes: 2 additions & 0 deletions backend/src/router.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@ const express = require("express");
const router = express.Router();

const PlayerControllers = require("./controllers/playerControllers");
const PartyControllers = require("./controllers/partyControllers");

router.get("/players", PlayerControllers.browse);
router.delete("/players/:id", PlayerControllers.destroy);
router.get("/party", PartyControllers.browse);

module.exports = router;
9 changes: 9 additions & 0 deletions backend/src/services/time.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
const transformTimeToMinute = (time) => {
const arr = time.split(":");

return +arr[0] * 60 + +arr[1];
};

module.exports = {
transformTimeToMinute,
};
2 changes: 2 additions & 0 deletions backend/src/tables.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,12 @@

// Import the manager modules responsible for handling data operations on the tables
const ItemManager = require("./models/ItemManager");
const PartyManager = require("./models/PartyManager");
const PlayerManager = require("./models/PlayerManager");

const managers = [
ItemManager,
PartyManager,
PlayerManager,
// Add other managers here
];
Expand Down
Loading