Skip to content

Commit

Permalink
Added total time for all user statuses endpoint and patched tests to …
Browse files Browse the repository at this point in the history
…run successfully!
  • Loading branch information
malee31 committed Dec 9, 2024
1 parent b31c358 commit c00230b
Show file tree
Hide file tree
Showing 4 changed files with 48 additions and 16 deletions.
44 changes: 35 additions & 9 deletions src/database/database-interface.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { makeNewApiKey } from "../utils/apiKey.js";
import { TESTING } from "../../config.js";
import db, { ApiKey, Session, SessionAssociation, User } from "./database.js";
import sequelize, { Op } from "sequelize";
import tableNames from "./table-names.js";
import db, { ApiKey, Session, User } from "./database.js";
import { Op, QueryTypes, col } from "sequelize";

// This file acts as an abstraction layer between the database and the code for easy compatibility with any database
// This file should contain methods to interact and manipulate database information
Expand Down Expand Up @@ -99,18 +99,38 @@ export async function getAllUsers() {

export async function getAllUsersWithStatus() {
const users = await User.findAll({
attributes: ["id", "first_name", "last_name"],
attributes: [
"id",
"first_name",
"last_name",
[
// Note the wrapping parentheses in the call below!
sequelize.literal(`(
SELECT SUM(endTime)
FROM ${tableNames.sessions} AS Sessions
WHERE User.password = Sessions.password
AND Sessions.endTime IS NOT NULL
)`),
"total_end",
],
[
// Note the wrapping parentheses in the call below!
sequelize.literal(`(
SELECT SUM(startTime)
FROM ${tableNames.sessions} AS Sessions
WHERE User.password = Sessions.password
AND Sessions.endTime IS NOT NULL
)`),
"total_start",
]
],
include: [{
model: Session,
association: User.hasMany(Session, {
as: "session_data",
sourceKey: "session",
foreignKey: "session_id"
}),
association: SessionAssociation,
attributes: ["session_id", "startTime", "endTime"],
where: {
password: {
[Op.eq]: col('User.password')
[Op.eq]: "User.password"
}
},
required: false // This is effectively the Sequelize equivalent of a `LEFT JOIN` in SQL
Expand All @@ -133,6 +153,12 @@ export async function getAllUsersWithStatus() {
userStatus.session = null;
}

userStatus.total_sessions = 0;
if(userStatus["total_start"] && userStatus["total_end"]) {
userStatus.total_sessions = userStatus["total_end"] - userStatus["total_start"];
}
delete userStatus["total_start"];
delete userStatus["total_end"];
delete userStatus[`session_data.session_id`];
delete userStatus[`session_data.startTime`];
delete userStatus[`session_data.endTime`];
Expand Down
15 changes: 11 additions & 4 deletions src/database/database.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
*/

// Configure SQL credentials from environment variables
import { Sequelize, DataTypes, Model } from "sequelize";
import { DataTypes, Model, Sequelize } from "sequelize";
import tableNames from "./table-names.js";
import { MYSQL_DATABASE, MYSQL_HOST, MYSQL_PASSWORD, MYSQL_USER, PRODUCTION, TESTING } from "../../config.js";

Expand Down Expand Up @@ -114,7 +114,7 @@ User.init({
type: DataTypes.INTEGER,
references: {
model: Session,
key: "session_id"
key: "session_id",
},
defaultValue: null,
onDelete: "CASCADE"
Expand All @@ -125,6 +125,13 @@ User.init({
timestamps: false
});

export const SessionAssociation = User.hasMany(Session, {
as: "session_data",
foreignKey: "session_id",
sourceKey: "session",
constraints: false
});

// Generates tables if they do not exist
// WARNING: Will not modify tables with an updated schema if they already exist
async function createTables() {
Expand All @@ -136,12 +143,12 @@ async function createTables() {

// Purges all tables and data
// Restarting the server should regenerate new tables using createTables()
async function dropTables() {
async function dropTables(logging = true) {
// All logging turned on for this extremely destructive action
await sequelize.drop({
cascade: true,
benchmark: true,
logging: console.info
logging: logging ? console.info : false
});
}

Expand Down
1 change: 0 additions & 1 deletion src/routes/users/users.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@ usersRouter.get("/", async (req, res) => {

usersRouter.get("/status", async (req, res) => {
// List all user data with statuses
// TODO: Join with sessions
const allUsers = await getAllUsersWithStatus();
return res.status(200).send({
ok: true,
Expand Down
4 changes: 2 additions & 2 deletions src/utils/testUtils.js
Original file line number Diff line number Diff line change
Expand Up @@ -109,8 +109,8 @@ export async function insertTestSession(_testSessionObj) {
export async function associateSession(password, sessionId) {
// TODO: Check for errors and success
const [_, sessionAffectedRows] = await db.query(`UPDATE ${tableNames.users}
SET session = ?
WHERE password = ?`, {
SET session = ?
WHERE password = ?`, {
type: QueryTypes.UPDATE,
replacements: [sessionId, password]
});
Expand Down

0 comments on commit c00230b

Please sign in to comment.