diff --git a/backend/index.ts b/backend/index.ts new file mode 100644 index 0000000..fbfeb81 --- /dev/null +++ b/backend/index.ts @@ -0,0 +1,115 @@ +import express from "express"; +import dotenv from "dotenv"; +import os from "os"; +import bodyParser from "body-parser"; +import mongoose from "mongoose"; +import cors from "cors"; +import cloudinary from "cloudinary"; + +import path from "path"; + +// Middleware +import tracker from "./middleware/tracker.js"; +import setHeaders from "./utils/setHeaders.js"; + +// Auth +import register from "./routes/auth/register.js"; +import login from "./routes/auth/login.js"; +import logout from "./routes/auth/logout.js"; + +// CRUD +import get_user from "./routes/crud/read/get_user.js"; +import get_machines from "./routes/crud/read/get_machines.js"; +import get_workouts from "./routes/crud/read/get_workouts.js"; +import update_user from "./routes/crud/update/update_user.js"; +import update_cardio from "./routes/crud/update/update_cardio.js"; +import add_machine from "./routes/crud/update/add_machine.js"; +import create_workout from "./routes/crud/create/create_workout.js"; +import create_machine from "./routes/crud/create/create_machine.js"; +import update_status from "./routes/crud/update/update_status.js"; +import end_workout from "./routes/crud/delete/end_workout.js"; +import rate_workout from "./routes/crud/update/rate_workout.js"; +import add_exercise from "./routes/crud/create/create_exercise.js"; +import update_set from "./routes/crud/update/update_set.js"; + +dotenv.config(); + +const PORT = process.env.PORT; + + + +declare module 'cloudinary' { + export function config(conf: ConfigOptions): void; +} + +interface ConfigOptions { + cloud_name: string; + api_key: string; + api_secret: string; +} + +// Image Storage +cloudinary.config({ + cloud_name: process.env.CLOUD_NAME, + api_key: process.env.CLOUDINARY_API_KEY, + api_secret: process.env.CLOUDINARY_API_SECRET +}); + +const app = express(); + +app.use(bodyParser.urlencoded({ extended: true })); +// Parse incoming requests data as JSON. +app.use(bodyParser.json()); +// Allow cross-origin requests. +app.use(cors()); +// Track the requests to the backend. +app.use(tracker); +// Set the headers for the requests. +app.use(setHeaders); +// Register a user endpoint. +app.use("/api/users/register", register); +// Login a user endpoint. +app.use("/api/users/login", login); +// Logout a user endpoint. +app.use("/api/users/logout", logout); +// Get user endpoint. +app.use("/api/users/get", get_user); +// Create a new workout for a user. +app.use("/api/workouts/create", create_workout); +// Add a new machine to a workout. +app.use("/api/workout/machines/add", add_machine); +// Update cardio machine 'x' with a distance and time spent. +app.use("/api/workout/machines/cardio/add", update_cardio); +// Add a machine to the dixon collectiion +app.use("/api/machine/create", create_machine); +// Get all the machines in the dixon collection +app.use("/api/machines/get", get_machines); +// Update a machine's status in a workout. +app.use("/api/machine/update_status", update_status); +// Update the user's profile +app.use("/api/users/update", update_user); +// Get the user's workout and saved workouts. +app.use("/api/workouts/get", get_workouts); +// End the user's workout. +app.use("/api/workout/end", end_workout); +// Rate the user's workout. +app.use("/api/workout/rate", rate_workout); +// Add an exercise to a workout. +app.use("/api/workout/exercises/add", add_exercise); +// Add a sets to a strength machine. +app.use("/api/workout/machines/sets/add", update_set); + +app.get("/api", (req, res) => { + res.send({ username: os.userInfo().username }); +}); + +app.listen(PORT, () => { + console.log(`⚡️ [server]: Server is running at http://localhost:${PORT}`); +}); + +const uri = process.env.URI as string; + +mongoose + .connect(uri) + .then(() => console.log("⚡️ [server]: MongoDB connection established...")) + .catch((error) => console.error("⚡️ [server]: MongoDB connection failed:", error.message)); diff --git a/backend/middleware/tracker.js b/backend/middleware/tracker.ts similarity index 100% rename from backend/middleware/tracker.js rename to backend/middleware/tracker.ts diff --git a/backend/models/dixon.ts b/backend/models/dixon.ts new file mode 100644 index 0000000..e071148 --- /dev/null +++ b/backend/models/dixon.ts @@ -0,0 +1,44 @@ +import mongoose from "mongoose"; + +type DixonType = mongoose.Document & { + machine_name: string; + machine_id: string; + machine_image: string; + machine_type: string; + machine_status: boolean; +} + +const dixonSchema = new mongoose.Schema({ + machine_name: { + type: String, + required: true, + unique: true + }, + machine_id: { + // uuid + type: String, + required: true, + unique: true + }, + machine_image: { + // cloudinary + type: String, + required: true, + unique: true + }, + machine_type: { + type: String, + enum: ["Cardio", "Strength", "Other", "None"], + default: "None", + required: true + }, + machine_status: { + // 1,true = available, 0,false = in use + type: Boolean, + required: true, + default: true + } +}); + +const Dixon = mongoose.model("Dixon", dixonSchema); +export default Dixon; diff --git a/backend/models/user.ts b/backend/models/user.ts new file mode 100644 index 0000000..80c3af9 --- /dev/null +++ b/backend/models/user.ts @@ -0,0 +1,129 @@ +import mongoose from "mongoose"; +import dotenv from "dotenv"; +import { Workout } from "./workout.js"; +dotenv.config(); +import { Schema, model, connect } from 'mongoose'; + +enum EBloodType { + A = "A", + B = "B", + AB = "AB", + O = "O", + None = "" +} + +type UserType = mongoose.Document & { + username: string; + pin: string; + initLogin?: boolean; + weight: number; + height: number; + BMI: number; + bloodType?: string; + createdAt: Date; + updatedAt: Date; + savedWorkouts: typeof Workout[]; + workouts: typeof Workout[]; + firstName?: string; + lastName?: string; + age?: number; + timestamps?: boolean; +} + +const userSchema = new mongoose.Schema({ + username: { + type: String, + required: true, + minlength: 3, + maxlength: 200, + unique: false + }, + pin: { + type: String, + required: true, + minlength: 4, + maxlength: 99999, + unique: false + }, + initLogin: { + type: Boolean, + default: true + }, + weight: { + type: Number, + default: 0, + validate: { + validator: Number.isInteger, + message: "{VALUE} is not an integer value" + }, + required: [true, "Weight is required"], + unique: false + }, + height: { + type: Number, + default: 0, + validate: { + validator: Number.isInteger, + message: "{VALUE} is not an integer value" + }, + required: [true, "Height is required"], + unique: false + }, + BMI: { + type: Number, + default: 0, + required: [true, "BMI is required"], + unique: false + }, + bloodType: { + type: String, + enum: ["O+", "O-", "A+", "A-", "B+", "B-", "AB+", "AB-", ""], + required: false, + unique: false, + uppercase: true + }, + // loginDateTime: { + // type: Date, + // required: false, + // minlength: 3, + // maxlength: 200, + // unique: false + // }, + // logoutDateTime: { + // type: Date, + // required: false, + // minlength: 3, + // maxlength: 200, + // unique: false + // }, + savedWorkouts: [Workout.schema], + workouts: [Workout.schema], + firstName: { + type: String, + required: false + }, + lastName: { + type: String, + required: false + }, + age: { + type: Number, + default: 0, + min: 0, + max: 150, + validate: { + validator: Number.isInteger, + message: "{VALUE} is not an integer value" + }, + required: false, + unique: false + }, + timestamps: { + type: Boolean, + default: true + } +}); + +const User = mongoose.model("User", userSchema); + +export default User; \ No newline at end of file diff --git a/backend/models/workout.ts b/backend/models/workout.ts new file mode 100644 index 0000000..68d38c4 --- /dev/null +++ b/backend/models/workout.ts @@ -0,0 +1,172 @@ +import mongoose from "mongoose"; +import { Schema, model, connect } from 'mongoose'; +import dotenv from "dotenv"; + +dotenv.config(); + +enum EWorkoutType { + Cardio = "Cardio", + Strength = "Strength", + Other = "Other", + None = "None" +} + +enum EWorkoutIntensity { + Low = "Low", + Medium = "Medium", + High = "High", + None = "None" +} + +type ExerciseType = mongoose.Document & { + exercise_name: string; +} + +type ExerciseSetType = mongoose.Document & { + reps?: number; + weight?: number; +} + +type MachineType = mongoose.Document & { + username: string; + machine_name: string; + machine_type: string; + machine_status: boolean; + distance: number; + timeSpent: number; + sets: ExerciseSetType[]; + machine_id: string; +} + +type WorkoutType = mongoose.Document & { + username: string; + workOutType: EWorkoutType; + workOutIntensity: string; + machines: MachineType[]; + workoutStartTimestamp: Date; + workoutEndTimestamp: Date; + effortLevel: number; + workoutDuration: number; + tirednessLevel: number; + workoutExercises: ExerciseType[]; +} + + +const exerciseSchema = new mongoose.Schema({ + exercise_name: { + type: String, + required: true, + } +}); + +const machineSchema = new mongoose.Schema({ + username: { + type: String, + required: true, + unqiue: true + }, + machine_name: { + type: String, + required: true + }, + machine_type: { + type: String, + enum: ["Cardio", "Strength", "Other", "None"], + default: "None", + required: true + }, + machine_status: { + // 1,true = available, 0,false = in use + type: Boolean, + required: true + }, + distance: { + // in miles + type: Number, + required: false + }, + timeSpent: { + // in minutes + type: Number, + required: false + }, + sets: [ + { + reps: { + type: Number, + required: false, + default: 0 + }, + weight: { + type: Number, + required: false, + default: 0 + } + } + ], + machine_id: { + type: String, + required: true, + unique: true + } +}); + +const workoutSchema = new mongoose.Schema({ + username: { + type: String, + required: true, + unqiue: false + }, + workOutType: { + enum: [EWorkoutType.Cardio, EWorkoutType.Strength, EWorkoutType.Other, EWorkoutType.None], + type: String, + required: false, + unique: false, + default: EWorkoutType.None + }, + workOutIntensity: { + enum: [EWorkoutIntensity.Low, EWorkoutIntensity.Medium, EWorkoutIntensity.High, EWorkoutIntensity.None], + type: String, + required: false, + unique: false, + default: EWorkoutIntensity.None + }, + machines: [machineSchema], + workoutStartTimestamp: { + type: Date, + required: false, + unique: false + }, + workoutEndTimestamp: { + type: Date, + required: false, + unique: false + }, + effortLevel: { + type: Number, + required: false, + min: 0, + max: 10, + unique: false + }, + tirednessLevel: { + type: Number, + required: false, + min: 0, + max: 10, + unique: false + }, + workoutDuration: { + // in minutes + type: Number, + required: false, + unique: false + }, + workoutExercises: [exerciseSchema] +}); + +const Workout = mongoose.model("Workout", workoutSchema); +const Machine = mongoose.model("Machine", machineSchema); +const Exercise = mongoose.model("Exercise", exerciseSchema); + +export { Workout, Machine, Exercise, EWorkoutType, EWorkoutIntensity }; diff --git a/backend/package.json b/backend/package.json index 1b3b6f8..5732368 100644 --- a/backend/package.json +++ b/backend/package.json @@ -2,11 +2,14 @@ "name": "progress-backend", "version": "1.0.0", "description": "Backend for ProgressAD", - "main": "index.js", + "main": "dist/index", + "typings": "dist/index", "scripts": { - "start": "node index.js", - "server": "nodemon index.js", - "frontend": "npm start --prefix frontend" + "start": "node dist/index.js", + "server": "nodemon dist/index.js", + "dev": "concurrently \"npx tsc --watch\" \"nodemon dist/index.js\"", + "frontend": "npm start --prefix frontend", + "build": "npx tsc" }, "repository": { "type": "git", @@ -22,6 +25,7 @@ "url": "https://github.com/TrackMeAtDixon/Progress/issues" }, "dependencies": { + "@types/cors": "^2.8.13", "bcrypt": "^5.1.0", "body-parser": "^1.20.1", "cloudinary": "^1.32.0", @@ -35,8 +39,11 @@ "uuid": "^9.0.0" }, "devDependencies": { + "@types/express": "^4.17.15", + "@types/node": "^18.11.18", "nodemon": "^2.0.20", - "prettier": "2.7.1" + "prettier": "2.7.1", + "typescript": "^4.9.4" }, "type": "module" } diff --git a/backend/tsconfig.json b/backend/tsconfig.json new file mode 100644 index 0000000..444c9af --- /dev/null +++ b/backend/tsconfig.json @@ -0,0 +1,103 @@ +{ + "compilerOptions": { + /* Visit https://aka.ms/tsconfig to read more about this file */ + + /* Projects */ + // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */ + // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ + // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */ + // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */ + // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ + // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ + + /* Language and Environment */ + "target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ + // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ + // "jsx": "preserve", /* Specify what JSX code is generated. */ + // "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */ + // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */ + // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */ + // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */ + // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */ + // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */ + // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ + // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ + // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */ + + /* Modules */ + "module": "NodeNext", /* Specify what module code is generated. */ + // "rootDir": "./", /* Specify the root folder within your source files. */ + // "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */ + // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ + // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ + // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ + // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */ + // "types": [], /* Specify type package names to be included without being referenced in a source file. */ + // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ + // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */ + // "resolveJsonModule": true, /* Enable importing .json files. */ + // "noResolve": true, /* Disallow 'import's, 'require's or ''s from expanding the number of files TypeScript should add to a project. */ + + /* JavaScript Support */ + "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */ + "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ + "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */ + + /* Emit */ + // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ + // "declarationMap": true, /* Create sourcemaps for d.ts files. */ + // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */ + // "sourceMap": true, /* Create source map files for emitted JavaScript files. */ + // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */ + "outDir": "./dist", /* Specify an output folder for all emitted files. */ + // "removeComments": true, /* Disable emitting comments. */ + // "noEmit": true, /* Disable emitting files from a compilation. */ + // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */ + // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */ + // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */ + // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */ + // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ + // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */ + // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */ + // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */ + // "newLine": "crlf", /* Set the newline character for emitting files. */ + // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */ + // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */ + // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */ + // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */ + // "declarationDir": "./", /* Specify the output directory for generated declaration files. */ + // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */ + + /* Interop Constraints */ + // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */ + // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ + "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */ + // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */ + "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ + + /* Type Checking */ + "strict": true, /* Enable all strict type-checking options. */ + "noImplicitAny": false, /* Enable error reporting for expressions and declarations with an implied 'any' type. */ + "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */ + // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */ + // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */ + // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */ + // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */ + // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */ + // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */ + // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */ + // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */ + // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */ + // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */ + // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */ + // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */ + // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */ + // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */ + // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */ + // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */ + + /* Completeness */ + // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ + "skipLibCheck": true /* Skip type checking all .d.ts files. */ + } +}