Files
TurboTrades/QUICK_REFERENCE.md
2026-01-10 04:57:43 +00:00

294 lines
5.9 KiB
Markdown

# TurboTrades Quick Reference Card
## 🚀 Quick Start (30 seconds)
```bash
npm install # Install dependencies
# Edit .env - add your STEAM_API_KEY
mongod # Start MongoDB
npm run dev # Start server
```
**Test it:** Open http://localhost:3000/health
---
## 📁 Project Structure (At a Glance)
```
TurboTrades/
├── index.js ⭐ Main entry point
├── config/ 🔧 Configuration
├── middleware/ 🛡️ Authentication
├── models/ 📊 Database schemas
├── routes/ 🛤️ API endpoints
└── utils/ 🔨 Helpers (JWT, WebSocket)
```
---
## 🔌 Essential API Endpoints
| Endpoint | Method | Auth | Description |
|----------|--------|------|-------------|
| `/health` | GET | ❌ | Health check |
| `/auth/steam` | GET | ❌ | Login with Steam |
| `/auth/me` | GET | ✅ | Get current user |
| `/auth/refresh` | POST | 🔄 | Refresh token |
| `/auth/logout` | POST | ✅ | Logout |
| `/user/profile` | GET | ✅ | User profile |
| `/user/trade-url` | PATCH | ✅ | Update trade URL |
| `/ws` | WS | Optional | WebSocket |
---
## 🔑 Environment Variables (Required)
```env
MONGODB_URI=mongodb://localhost:27017/turbotrades
STEAM_API_KEY=YOUR_STEAM_API_KEY_HERE
SESSION_SECRET=random-string
JWT_ACCESS_SECRET=random-string
JWT_REFRESH_SECRET=random-string
```
**Generate secrets:**
```bash
node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
```
---
## 📡 WebSocket Usage
### Client Connection
```javascript
const ws = new WebSocket('ws://localhost:3000/ws?token=YOUR_TOKEN');
ws.onmessage = (e) => {
const msg = JSON.parse(e.data);
console.log(msg);
};
```
### Server Broadcasting
```javascript
import { wsManager } from './utils/websocket.js';
// Broadcast to all
wsManager.broadcastPublic('price_update', { price: 99 });
// Send to specific user (by Steam ID)
wsManager.sendToUser(steamId, { type: 'notification', data: {...} });
```
---
## 🛡️ Using Middleware
```javascript
import { authenticate, requireStaffLevel } from './middleware/auth.js';
// Require authentication
fastify.get('/protected', {
preHandler: authenticate
}, handler);
// Require staff level
fastify.post('/admin', {
preHandler: [authenticate, requireStaffLevel(3)]
}, handler);
```
---
## 🗄️ Database Quick Reference
```javascript
// Import model
import User from './models/User.js';
// Find user
const user = await User.findOne({ steamId: '123' });
// Update user
user.balance += 100;
await user.save();
// Create user
const newUser = new User({ username: 'Player' });
await newUser.save();
```
---
## 🔧 Common Commands
```bash
# Development
npm run dev # Auto-reload on changes
npm start # Production mode
# MongoDB
mongod # Start MongoDB
mongosh # MongoDB shell
use turbotrades # Select database
db.users.find() # View users
# Testing
curl http://localhost:3000/health
open test-client.html # WebSocket tester
# PM2 (Production)
pm2 start index.js --name turbotrades
pm2 logs turbotrades
pm2 restart turbotrades
```
---
## 🎯 Adding Features
### New Route
```javascript
// routes/myroute.js
export default async function myRoutes(fastify, options) {
fastify.get('/my-endpoint', {
preHandler: authenticate
}, async (request, reply) => {
return { success: true };
});
}
// index.js
import myRoutes from './routes/myroute.js';
await fastify.register(myRoutes);
```
### New Model
```javascript
// 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);
```
---
## 🔒 JWT Token Flow
```
1. Login → Steam OAuth → Generate JWT
2. Store in httpOnly cookie (secure)
3. Client sends cookie with requests
4. Server verifies JWT
5. Token expires → Use refresh token
6. Logout → Clear cookies
```
**Token Lifetimes:**
- Access Token: 15 minutes
- Refresh Token: 7 days
---
## 🐛 Debugging
```bash
# Check if server is running
curl http://localhost:3000/health
# Check MongoDB connection
mongosh --eval "db.version()"
# Check port usage
lsof -i :3000 # Mac/Linux
netstat -ano | find "3000" # Windows
# View logs
npm run dev # Shows all logs
pm2 logs turbotrades # PM2 logs
```
---
## 📚 Documentation Files
- **README.md** → Complete documentation
- **QUICKSTART.md** → 5-minute setup
- **WEBSOCKET_GUIDE.md** → WebSocket details
- **ARCHITECTURE.md** → System design
- **STRUCTURE.md** → File organization
- **COMMANDS.md** → Full command list
- **THIS FILE** → Quick reference
---
## ⚡ Performance Tips
✅ Add database indexes
✅ Enable Redis for sessions
✅ Use MongoDB Atlas (production)
✅ Enable PM2 cluster mode
✅ Add CDN for static assets
✅ Use connection pooling
---
## 🔐 Security Checklist
```bash
✅ HTTPS/WSS in production
✅ Strong JWT secrets
COOKIE_SECURE=true
✅ Rate limiting enabled
✅ Input validation
✅ MongoDB authentication
✅ Regular security updates
✅ Environment variables secured
```
---
## 🆘 Common Issues
**Port in use?**
```bash
lsof -i :3000
kill -9 <PID>
```
**MongoDB won't start?**
```bash
mongod --dbpath ~/data/db
```
**Module not found?**
```bash
rm -rf node_modules package-lock.json
npm install
```
**Steam auth fails?**
Check `STEAM_API_KEY` in `.env`
---
## 📞 Getting Help
1. Check `README.md` for detailed docs
2. Review example in `routes/marketplace.example.js`
3. Test WebSocket with `test-client.html`
4. Check error logs in terminal
---
**⭐ Remember:** All imports use `.js` extension (ES modules)
**🚀 Ready to build! Check QUICKSTART.md for step-by-step setup.**