Skip to content

Commit

Permalink
Merge branch 'main' into feature/users-routes
Browse files Browse the repository at this point in the history
  • Loading branch information
Cow-Van authored Jan 16, 2024
2 parents 8039218 + 6a8e9ba commit 8477b6f
Show file tree
Hide file tree
Showing 6 changed files with 75 additions and 8 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"rimraf": "./node_modules/rimraf/bin.js",
"start": "npm run build && node ./dist/app.js",
"build": "rimraf ./dist/ && tsc --project basic.tsconfig.json",
"test": "rimraf ./test/ && tsc --project test.tsconfig.json && cross-env NODE_ENV=testing mocha ./test/tests/**/*.spec.js --exit --timeout 10000"
"test": "rimraf ./test/ && tsc --project test.tsconfig.json && cross-env NODE_ENV=testing mocha ./test/tests/**/*.spec.js ./test/e2e/**/*.spec.js --exit --timeout 10000"
},
"repository": {
"type": "git",
Expand Down
2 changes: 2 additions & 0 deletions src/api/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import express from "express"

import infoRouter from "./routes/info";
import usersRouter from "./routes/users";

const router = express.Router();

router.use("/info", infoRouter);
router.use("/users", usersRouter);

export default router;
51 changes: 51 additions & 0 deletions src/api/routes/info.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import express from "express";

import { getAllUsers, getUserById } from "../../models/User.model";
import { RowNotFoundError } from "../../utils/errors";

const router = express.Router();

// Returns user_id, first_name, last_name, signed_in, last_signed_in, total_time for all users
router.get("/users", async (req, res) => {
const users = await getAllUsers();
users.map((user: any) => {delete user.password}); // Remove password field

return res.status(200).json({
description: "Returning all users",
users: users,
})
});

// Return user_id, first_name, last_name, signed_in, last_signed_in, total_time of user with given valid ID
router.get("/users/:id", async (req, res) => {
// Is user ID valid?
if (isNaN(Number(req.params.id))) {
return res.status(404).json({
description: `User of id: ${req.params.id} not found`,
});
}

let user;

try {
user = await getUserById(Number(req.params.id));
} catch (err) {
if (err instanceof RowNotFoundError) {
return res.status(404).json({
description: err.message,
});
}

return res.sendStatus(500);
}


delete (user as any).password; // Remove password field

return res.status(200).json({
description: "User found",
user: user,
});
});

export default router;
1 change: 1 addition & 0 deletions src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ const app = express();

app.use(middleware.json);
app.use(middleware.errorHandler);

app.use("/api/v1", api);

app.listen(process.env.PORT, () => {
Expand Down
19 changes: 16 additions & 3 deletions src/models/User.model.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { ResultSetHeader, RowDataPacket } from "mysql2";

import database from "../database";
import { RowNotFoundError } from "../utils/errors";
import updateBuilder from "../utils/updateBuilder";
Expand All @@ -7,7 +8,7 @@ interface User {
user_id: number;
first_name: string;
last_name: string;
password: number;
password: string;
signed_in: boolean;
last_signed_in: number;
total_time: number;
Expand All @@ -22,7 +23,18 @@ async function getAllUsers(): Promise<UserRowDataPacket[]> {
return users;
}

async function getUserByPassword(password: number): Promise<User> {
async function getUserById(userId: number): Promise<User> {
const sql = "SELECT * FROM `users` WHERE user_id = ?";
const [users] = await database.query<User[]>(sql, [userId]);

Check failure on line 28 in src/models/User.model.ts

View workflow job for this annotation

GitHub Actions / build (18.x)

Type 'User[]' does not satisfy the constraint 'OkPacket | RowDataPacket[] | ResultSetHeader[] | RowDataPacket[][] | OkPacket[] | ProcedureCallPacket'.

Check failure on line 28 in src/models/User.model.ts

View workflow job for this annotation

GitHub Actions / build (18.x)

Type 'User[]' does not satisfy the constraint 'OkPacket | RowDataPacket[] | ResultSetHeader[] | RowDataPacket[][] | OkPacket[] | ProcedureCallPacket'.

if (users.length < 1) {
throw new RowNotFoundError(`User of id: ${userId} not found in table: users`);
}

return users[0];
}

async function getUserByPassword(password: string): Promise<User> {
const sql = "SELECT * FROM `users` WHERE password = ?";
const [users] = await database.query<UserRowDataPacket[]>(sql, [password]);

Expand All @@ -36,7 +48,7 @@ async function getUserByPassword(password: number): Promise<User> {
async function createUser(
first_name: string,
last_name: string,
password: number
password: string
): Promise<User> {
const sql =
"INSERT INTO `users` (first_name, last_name, password) VALUES (?, ?, ?); SELECT user_id, first_name, last_name FROM users where password = ?";
Expand Down Expand Up @@ -67,6 +79,7 @@ async function deleteUser(password: number): Promise<boolean> {
export default User;
export {
getAllUsers,
getUserById,
getUserByPassword,
createUser,
updateUser,
Expand Down
8 changes: 4 additions & 4 deletions src/utils/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,17 +23,17 @@ function newLogFileName(type: string): string {
pathSegments.push("logs");
if (process.env.NODE_ENV === "testing") { pathSegments.push("tests") }
pathSegments.push(type);
pathSegments.push(type + "_" + dateToYYYYMMDD());
pathSegments.push(type + "_" + dateToTimestamp());

return pathSegments.join("/");
return pathSegments.join("/") + ".log";
}

function dateToYYYYMMDD(date?: Date): string {
function dateToTimestamp(date?: Date): string {
if (!date) {
date = new Date();
}

return date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate();
return date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate() + "-" + date.getTime();
}

export default logger;

0 comments on commit 8477b6f

Please sign in to comment.