Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

12 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Server Icon

βš™οΈ GYM ENGINE β€” SERVER

Robust REST API Backend for the Gym Engine Platform

Base URL: https://gym-engine-server.vercel.app/api/v1


πŸ“– Overview

The Gym Engine Server is a fully typed, production-ready REST API built with Express 5 and TypeScript. It powers all platform operations β€” authentication, user management, class scheduling, bookings, and role-based access control β€” for the Gym Engine frontend.


πŸ—‚οΈ Project Structure

gym-engine-server/
β”‚
β”œβ”€β”€ index.ts                  # Entry point β€” bootstraps app & DB connection
β”‚
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ config/
β”‚   β”‚   └── db.ts             # MongoDB connection setup
β”‚   β”‚
β”‚   β”œβ”€β”€ controllers/
β”‚   β”‚   β”œβ”€β”€ auth.controller.ts
β”‚   β”‚   β”œβ”€β”€ user.controller.ts
β”‚   β”‚   β”œβ”€β”€ class.controller.ts
β”‚   β”‚   β”œβ”€β”€ schedule.controller.ts
β”‚   β”‚   └── booking.controller.ts
β”‚   β”‚
β”‚   β”œβ”€β”€ models/
β”‚   β”‚   β”œβ”€β”€ user.model.ts
β”‚   β”‚   β”œβ”€β”€ class.model.ts
β”‚   β”‚   β”œβ”€β”€ schedule.model.ts
β”‚   β”‚   └── booking.model.ts
β”‚   β”‚
β”‚   β”œβ”€β”€ routes/
β”‚   β”‚   β”œβ”€β”€ auth.routes.ts
β”‚   β”‚   β”œβ”€β”€ user.routes.ts
β”‚   β”‚   β”œβ”€β”€ class.routes.ts
β”‚   β”‚   β”œβ”€β”€ schedule.routes.ts
β”‚   β”‚   └── booking.routes.ts
β”‚   β”‚
β”‚   β”œβ”€β”€ middlewares/
β”‚   β”‚   β”œβ”€β”€ auth.middleware.ts  # JWT verification
β”‚   β”‚   β”œβ”€β”€ role.middleware.ts  # RBAC enforcement
β”‚   β”‚   └── error.middleware.ts # Global error handler
β”‚   β”‚
β”‚   └── utils/
β”‚       β”œβ”€β”€ generateToken.ts
β”‚       └── responseHelper.ts
β”‚
β”œβ”€β”€ dist/                      # Compiled JS output (auto-generated)
β”œβ”€β”€ .env                       # Environment variables
β”œβ”€β”€ tsconfig.json
└── package.json

πŸ“¦ Dependencies

Production

Package Version Purpose
express ^5.2.1 HTTP server & routing framework
mongodb ^7.2.0 MongoDB driver for database ops
jsonwebtoken ^9.0.3 JWT creation & verification
bcryptjs ^3.0.3 Password hashing & comparison
cors ^2.8.6 Cross-Origin Resource Sharing
cookie-parser ^1.4.7 Parse cookies from requests
dotenv ^17.4.2 Load environment variables
morgan ^1.10.1 HTTP request logger

Development

Package Version Purpose
typescript ^6.0.3 Type-safe JavaScript superset
ts-node-dev ^2.0.0 Dev server with hot reload
@types/express ^5.0.6 Express type definitions
@types/node ^25.6.0 Node.js type definitions
@types/jsonwebtoken ^9.0.10 JWT type definitions
@types/bcryptjs ^2.4.6 bcryptjs type definitions
@types/cors ^2.8.19 CORS type definitions
@types/morgan ^1.9.10 Morgan type definitions
@types/cookie-parser ^1.4.10 Cookie-parser type definitions

πŸš€ Getting Started

Prerequisites

  • Node.js v18+
  • MongoDB (Atlas or local)
  • npm or yarn

1. Clone the Repository

git clone https://github.com/tuhin360/gym-engine-server.git
cd gym-engine-server

2. Install Dependencies

npm install

3. Configure Environment Variables

Create a .env file in the root:

# Server
PORT=5000

# Database
MONGO_URI=mongodb+srv://<user>:<password>@cluster.mongodb.net/gym-engine

# Auth
JWT_SECRET=your_super_secret_jwt_key

# Frontend
FRONTEND_URL=http://localhost:3000

4. Run the Server

# Development (hot reload via ts-node-dev)
npm run dev

# Production (compile β†’ run)
npm start

Server starts at http://localhost:5000


πŸ“œ Available Scripts

Script Command Description
dev ts-node-dev --respawn --transpile-only index.ts Dev server with hot reload
start tsc && node dist/index.js Compile TypeScript then run
test (not yet configured) Test runner placeholder

🌐 API Endpoints

πŸ” Auth Routes β€” /api/v1/auth

Method Endpoint Access Description
POST /register Public Register a new user
POST /login Public Login & receive JWT
POST /logout Auth Invalidate session
GET /me Auth Get current user profile

πŸ‘€ User Routes β€” /api/v1/users

Method Endpoint Access Description
GET / Admin Get all users
GET /:id Admin/Self Get user by ID
PATCH /:id Admin/Self Update user details
DELETE /:id Admin Delete a user
PATCH /:id/role Admin Update user role

πŸ‹οΈ Class Routes β€” /api/v1/classes

Method Endpoint Access Description
GET / Public Get all classes
GET /:id Public Get class by ID
POST / Admin/Trainer Create new class
PATCH /:id Admin/Trainer Update class
DELETE /:id Admin Delete class

πŸ“… Schedule Routes β€” /api/v1/schedules

Method Endpoint Access Description
GET / Public Get all schedules
POST / Admin/Trainer Create schedule slot
PATCH /:id Admin/Trainer Update schedule
DELETE /:id Admin Delete schedule

πŸ“‹ Booking Routes β€” /api/v1/bookings

Method Endpoint Access Description
GET / Admin Get all bookings
GET /my Member Get own bookings
POST / Member Create a booking
DELETE /:id Member/Admin Cancel a booking

πŸ” Authentication Flow

Client                        Server
  β”‚                              β”‚
  │─── POST /auth/login ────────▢│
  β”‚         { email, password }  β”‚
  β”‚                              │── bcryptjs.compare()
  β”‚                              │── JWT sign (role + id)
  │◀── { token, user } ─────────│
  β”‚                              β”‚
  │─── GET /protected ──────────▢│
  β”‚     Authorization: Bearer    │── verifyToken middleware
  β”‚                              │── checkRole middleware
  │◀── { protected data } ──────│

πŸ›‘οΈ Middleware Stack

Request
   β”‚
   β–Ό
morgan()          β†’ Logs method, URL, status, response time
cors()            β†’ Validates origin against FRONTEND_URL
express.json()    β†’ Parses JSON request bodies
cookieParser()    β†’ Parses cookies (refresh tokens etc.)
   β”‚
   β–Ό
Route Handler
   β”‚
   β–Ό
authMiddleware    β†’ Verifies JWT from Authorization header
roleMiddleware    β†’ Enforces role-based access (Admin / Trainer / Member)
   β”‚
   β–Ό
Controller Logic
   β”‚
   β–Ό
errorMiddleware   β†’ Catches thrown errors, formats JSON error response

πŸ—„οΈ Data Models

User

{
  _id:        ObjectId,
  name:       string,
  email:      string,       // unique
  password:   string,       // bcrypt hashed
  role:       "admin" | "trainer" | "member" | "non-member",
  createdAt:  Date,
  updatedAt:  Date
}

Class

{
  _id:         ObjectId,
  title:       string,
  description: string,
  category:    "basic" | "yoga" | "bodybuilding" | "muscle",
  trainer:     ObjectId,    // ref β†’ User
  capacity:    number,
  createdAt:   Date
}

Schedule

{
  _id:       ObjectId,
  class:     ObjectId,      // ref β†’ Class
  trainer:   ObjectId,      // ref β†’ User
  date:      Date,
  startTime: string,
  endTime:   string,
  slots:     number
}

Booking

{
  _id:       ObjectId,
  user:      ObjectId,      // ref β†’ User
  schedule:  ObjectId,      // ref β†’ Schedule
  status:    "confirmed" | "cancelled",
  bookedAt:  Date
}

βš™οΈ TypeScript Configuration

{
  "compilerOptions": {
    "target": "ES2020",
    "module": "commonjs",
    "strict": true,
    "esModuleInterop": true,
    "outDir": "./dist",
    "rootDir": "./",
    "skipLibCheck": true
  },
  "include": ["**/*.ts"],
  "exclude": ["node_modules", "dist"]
}

πŸ”’ Security Practices

  • βœ… Passwords hashed with bcryptjs (salt rounds: 10+)
  • βœ… Auth via short-lived JWT tokens
  • βœ… Role enforcement on every protected route
  • βœ… CORS restricted to known frontend origin
  • βœ… Environment secrets loaded via dotenv (never committed)
  • βœ… All inputs validated before database operations

πŸš€ Deployment

The server is deployed on Vercel using serverless functions.

# Install Vercel CLI
npm i -g vercel

# Deploy
vercel --prod

Make sure all environment variables from .env are added to your Vercel project settings.


πŸ—ΊοΈ Roadmap

  • JWT authentication & role-based access
  • Class & schedule management APIs
  • Booking system
  • Morgan logging
  • πŸ”” WebSocket notifications (Socket.io)
  • πŸ’¬ Trainer–Member messaging API
  • πŸ“Š Advanced analytics endpoints
  • βœ… Jest unit & integration tests
  • 🐳 Dockerize for local dev
  • πŸ” Refresh token rotation

πŸ‘¨β€πŸ’» Author

Jahedi Alam Tuhin

Jahedi Alam Tuhin

GitHub


⭐ Star this repo if it helped you β€” it keeps the project alive!

Made with ❀️ by Jahedi Alam Tuhin

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

Packages

Contributors

Languages