9.1 KiB
TurboTrades Project Structure
Clean and simple structure with everything in the root directory.
📁 Directory Tree
TurboTrades/
├── config/ # Configuration files
│ ├── database.js # MongoDB connection handler
│ ├── index.js # Environment variables loader
│ └── passport.js # Steam OAuth strategy setup
│
├── middleware/ # Custom Express/Fastify middleware
│ └── auth.js # JWT authentication & authorization
│
├── models/ # MongoDB/Mongoose schemas
│ └── User.js # User schema (Steam, 2FA, email, bans)
│
├── routes/ # API route handlers
│ ├── auth.js # Authentication routes (Steam login, logout, refresh)
│ ├── marketplace.example.js # Example marketplace implementation
│ ├── user.js # User profile & settings routes
│ └── websocket.js # WebSocket management routes
│
├── utils/ # Utility functions & helpers
│ ├── jwt.js # JWT token generation & verification
│ └── websocket.js # WebSocket manager with user mapping
│
├── .env # Environment variables (local config)
├── .env.example # Environment variables template
├── .gitignore # Git ignore rules
├── index.js # Main server entry point ⭐
├── package.json # Dependencies & npm scripts
│
└── Documentation/
├── ARCHITECTURE.md # System architecture & diagrams
├── COMMANDS.md # Command reference cheatsheet
├── PROJECT_SUMMARY.md # High-level project overview
├── QUICKSTART.md # 5-minute setup guide
├── README.md # Main documentation
├── STRUCTURE.md # This file
├── WEBSOCKET_GUIDE.md # WebSocket integration guide
└── test-client.html # WebSocket test interface
🎯 File Purposes
Core Files
index.js - Main server entry point
- Initializes Fastify server
- Registers all plugins (CORS, Helmet, WebSocket, etc.)
- Connects to MongoDB
- Registers all routes
- Starts the server
Configuration (config/)
config/index.js - Central configuration
- Loads environment variables from
.env - Exports config object used throughout the app
- Provides sensible defaults
config/database.js - Database connection
- Connects to MongoDB using Mongoose
- Handles connection errors and retries
- Graceful shutdown support
config/passport.js - Authentication strategy
- Configures passport-steam strategy
- Handles Steam OAuth flow
- Creates/updates users on login
Middleware (middleware/)
middleware/auth.js - Authentication & authorization
authenticate()- Requires valid JWT tokenoptionalAuthenticate()- Optional JWT verificationrequireStaffLevel()- Check staff permissionsrequireVerifiedEmail()- Require verified emailrequire2FA()- Require two-factor authverifyRefreshTokenMiddleware()- Verify refresh tokens
Models (models/)
models/User.js - User database schema
- Steam profile data (ID, username, avatar)
- Marketplace data (balance, trade URL)
- Email system (address, verification)
- Security (bans, 2FA, staff level)
- Timestamps (createdAt, updatedAt)
Routes (routes/)
routes/auth.js - Authentication endpoints
GET /auth/steam- Start Steam loginGET /auth/steam/return- OAuth callbackGET /auth/me- Get current userPOST /auth/refresh- Refresh access tokenPOST /auth/logout- Logout userGET /auth/verify- Verify token validity
routes/user.js - User management endpoints
GET /user/profile- Get user profilePATCH /user/trade-url- Update trade URLPATCH /user/email- Update email addressGET /user/verify-email/:token- Verify emailGET /user/balance- Get balanceGET /user/stats- Get user statisticsPATCH /user/intercom- Update intercom IDGET /user/:steamId- Public user profile
routes/websocket.js - WebSocket management
GET /ws- WebSocket connection endpointGET /ws/stats- Connection statisticsPOST /ws/broadcast- Broadcast to all (admin)POST /ws/send/:userId- Send to specific userGET /ws/status/:userId- Check online status
routes/marketplace.example.js - Example implementation
- Shows how to create marketplace routes
- Demonstrates WebSocket broadcasting
- Example purchase flow with notifications
Utils (utils/)
utils/jwt.js - JWT token utilities
generateAccessToken()- Create access token (15min)generateRefreshToken()- Create refresh token (7 days)generateTokenPair()- Create both tokensverifyAccessToken()- Verify access tokenverifyRefreshToken()- Verify refresh tokenisTokenExpired()- Check if token expired
utils/websocket.js - WebSocket manager
handleConnection()- Process new connectionsbroadcastPublic()- Send to all clientsbroadcastToAuthenticated()- Send to authenticated userssendToUser()- Send to specific userisUserConnected()- Check if user is online- User-to-socket mapping
- Heartbeat/ping-pong system
- Automatic cleanup of dead connections
🔄 Data Flow
Authentication Flow
Client → /auth/steam → Steam → /auth/steam/return → Generate JWT → Set Cookies → Client
API Request Flow
Client → Nginx → Fastify → Middleware → Route Handler → Database → Response
WebSocket Flow
Client → /ws → Authenticate → Map User → Send/Receive Messages → Broadcast
📦 Key Dependencies
{
"fastify": "High-performance web framework",
"mongoose": "MongoDB ODM",
"passport-steam": "Steam OAuth authentication",
"jsonwebtoken": "JWT token creation/verification",
"ws": "WebSocket implementation",
"@fastify/cookie": "Cookie parsing & setting",
"@fastify/cors": "CORS support",
"@fastify/helmet": "Security headers",
"@fastify/rate-limit": "Rate limiting",
"@fastify/websocket": "WebSocket plugin for Fastify"
}
🚀 Getting Started
-
Install dependencies
npm install -
Configure environment
cp .env.example .env # Edit .env with your Steam API key -
Start MongoDB
mongod -
Run the server
npm run dev
📝 Adding New Features
Adding a new route
- Create file in
routes/(e.g.,routes/trades.js) - Define your endpoints with proper middleware
- Import and register in
index.js
// routes/trades.js
export default async function tradesRoutes(fastify, options) {
fastify.get('/trades', { preHandler: authenticate }, async (req, reply) => {
// Your logic here
});
}
// index.js
import tradesRoutes from './routes/trades.js';
await fastify.register(tradesRoutes);
Adding a new model
- Create file in
models/(e.g.,models/Listing.js) - Define Mongoose schema
- Export the model
// models/Listing.js
import mongoose from 'mongoose';
const ListingSchema = new mongoose.Schema({
itemName: String,
price: Number,
seller: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }
}, { timestamps: true });
export default mongoose.model('Listing', ListingSchema);
Adding middleware
- Create or update file in
middleware/ - Export your middleware function
- Use in routes with
preHandler
// middleware/custom.js
export const myMiddleware = async (request, reply) => {
// Your logic
};
// In routes
fastify.get('/protected', {
preHandler: [authenticate, myMiddleware]
}, handler);
Adding utilities
- Create file in
utils/(e.g.,utils/email.js) - Export utility functions
- Import where needed
// utils/email.js
export const sendVerificationEmail = async (email, token) => {
// Email logic
};
// In routes
import { sendVerificationEmail } from '../utils/email.js';
🧪 Testing
# Health check
curl http://localhost:3000/health
# Test authenticated endpoint
curl http://localhost:3000/auth/me \
-H "Authorization: Bearer YOUR_TOKEN"
# Test WebSocket
open test-client.html
📚 Documentation Files
- README.md - Start here for complete overview
- QUICKSTART.md - Get running in 5 minutes
- WEBSOCKET_GUIDE.md - Detailed WebSocket integration
- ARCHITECTURE.md - System design & diagrams
- COMMANDS.md - Command reference guide
- PROJECT_SUMMARY.md - High-level summary
- STRUCTURE.md - This file (project organization)
🎯 Why This Structure?
✅ Simple - No nested src/ folder, everything at root level
✅ Clear - Organized by function (routes, models, utils)
✅ Scalable - Easy to add new features
✅ Standard - Follows Node.js conventions
✅ Clean - Separation of concerns
✅ Maintainable - Easy to navigate and understand
Ready to build your marketplace! 🚀