A comprehensive REST API and WebSocket server for a multiplayer games, built with TypeScript, Node.js, Express, and MongoDB.
- User Authentication & Management: JWT-based authentication with user registration, login, and profile management
- Player Statistics: Comprehensive tracking of games played, wins, losses, rankings, and performance metrics
- Match History: Complete record of all games with detailed move history and results
- Real-time Game Sessions: WebSocket support for live game updates, moves, and chat
- Game Rules Engine: Support for different board sizes (9x9, 13x13, 19x19), time controls, and game settings
- Leaderboards: Multiple ranking systems based on wins, win rate, points, and streaks
- Language: TypeScript
- Runtime: Node.js
- Framework: Express.js
- Database: MongoDB with Mongoose ODM
- Authentication: JWT (JSON Web Tokens)
- Real-time: Socket.IO
- Validation: Express-validator
- Security: bcryptjs for password hashing
- Development: ts-node-dev for hot reloading
src/
├── models/ # MongoDB schemas and models
│ ├── Player.ts # User/player data model
│ ├── Match.ts # Completed game records
│ └── Game.ts # Active game sessions
├── routes/ # API route handlers
│ ├── auth.ts # Authentication endpoints
│ ├── players.ts # Player management
│ ├── matches.ts # Match history
│ └── games.ts # Active games
├── middleware/ # Custom middleware
│ └── auth.ts # JWT authentication
├── types/ # TypeScript interfaces
│ └── index.ts # All type definitions
└── server.ts # Main application entry point
POST /register- User registrationPOST /login- User loginPOST /logout- User logoutGET /me- Get current user profilePUT /profile- Update user profilePOST /change-password- Change passwordPOST /refresh- Refresh JWT token
GET /- List players with pagination and searchGET /leaderboard- Get leaderboards by different criteriaGET /:id- Get player by IDGET /:id/stats- Get detailed player statisticsGET /:id/matches- Get player's match historyPUT /:id/rank- Update player rankGET /online/status- Get online players
GET /- List matches with filtering and paginationGET /:id- Get match by ID with full detailsGET /:id/moves- Get match moves historyPOST /:id/end- End a matchGET /statistics/overview- Get overall match statisticsGET /statistics/player/:playerId- Get player match statisticsDELETE /:id- Delete a match
POST /- Create a new gameGET /- List available gamesGET /:gameId- Get game by IDPOST /:gameId/join- Join a gamePOST /:gameId/ready- Set player as readyPOST /:gameId/move- Make a movePOST /:gameId/pass- Pass turnPOST /:gameId/chat- Send chat messagePOST /:gameId/resign- Resign from gameDELETE /:gameId- Delete/abandon game
join-game- Join a game roomleave-game- Leave a game roomgame-move- Send game move data
new-game-created- New game availableplayer-joined- Player joined gameplayer-ready- Player ready statusgame-started- Game has startedmove-made- Move was madeturn-passed- Turn was passedchat-message- New chat messagegame-ended- Game has endedgame-deleted- Game was deleted
-
Clone the repository
git clone <repository-url> cd go-game-api
-
Install dependencies
npm install
-
Set up environment variables
cp env.example .env # Edit .env with your configuration -
Set up MongoDB
- Install MongoDB locally or use MongoDB Atlas
- Update the
MONGODB_URIin your.envfile
-
Build the project
npm run build
-
Start the server
# Development mode with hot reload npm run dev # Production mode npm start
# Server Configuration
PORT=3000
NODE_ENV=development
# MongoDB Connection
MONGODB_URI=mongodb://localhost:27017/go-game-db
# JWT Secret
JWT_SECRET=your-super-secret-jwt-key-here
# CORS Origins (Unity app domains)
CORS_ORIGIN=http://localhost:3000,http://localhost:8080npm run dev- Start development server with hot reloadnpm run build- Build TypeScript to JavaScriptnpm start- Start production servernpm run lint- Run ESLintnpm run lint:fix- Fix ESLint issuesnpm test- Run tests
The project uses strict TypeScript configuration with:
- Strict type checking
- No implicit any
- Strict null checks
- Unused variable detection
- Source maps for debugging
- User authentication and profile information
- Game statistics and rankings
- Game preferences and settings
- Online status tracking
- Completed game records
- Move history and board states
- Player results and scores
- Game metadata and timing
- Active game sessions
- Real-time board state
- Player connections and readiness
- Chat messages and game rules
All API responses follow a consistent format:
interface ApiResponse<T> {
message?: string;
data?: T;
error?: string;
errors?: ValidationError[];
}
interface PaginationResponse<T> {
data: T[];
pagination: {
currentPage: number;
totalPages: number;
totalItems: number;
hasNext: boolean;
hasPrev: boolean;
};
}The API uses JWT tokens for authentication. Include the token in the Authorization header:
Authorization: Bearer <your-jwt-token>
The API provides comprehensive error handling with appropriate HTTP status codes:
400- Bad Request (validation errors)401- Unauthorized (authentication required)403- Forbidden (insufficient permissions)404- Not Found (resource doesn't exist)500- Internal Server Error
- Password hashing with bcrypt
- JWT token expiration
- Input validation and sanitization
- CORS configuration
- Rate limiting (can be added)
The API is designed to work seamlessly with Unity:
- RESTful endpoints for game state management
- WebSocket support for real-time updates
- JSON responses optimized for Unity's JSON parsing
- CORS configured for Unity WebGL builds
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests if applicable
- Submit a pull request
MIT License - see LICENSE file for details
For questions or support, please open an issue on GitHub or contact the development team.