Skip to content

Commit e4a3cbd

Browse files
committed
feat: Add error handling middleware and rate limiter
- Implemented error handling middleware to manage various error types and responses. - Created a rate limiting middleware to control the number of requests from clients. - Added new routes for CodeChef, GeeksforGeeks, and discussion topics. - Developed utility functions for client interactions with CodeChef and GeeksforGeeks APIs. - Introduced helper functions for response handling and input validation.
0 parents  commit e4a3cbd

26 files changed

+4981
-0
lines changed

.env.example

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
PORT=3001
2+
NODE_ENV=development

.gitignore

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
node_modules/
2+
*.log
3+
*.env
4+
.env
5+
.env.local
6+
.env.development.local
7+
.env.test.local
8+
.env.production.local
9+
npm-debug.log*
10+
yarn-debug.log*
11+
yarn-error.log*
12+
.DS_Store
13+
.vscode/
14+
.idea/
15+
*.swp
16+
*.swo
17+
*~
18+
.nyc_output
19+
coverage/
20+
.cache/
21+
dist/
22+
build/

IMPLEMENTATION_SUMMARY.md

Lines changed: 128 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,128 @@
1+
# 🎉 LeetCode & CodeChef API - Implementation Complete!
2+
3+
## ✅ Successfully Implemented
4+
5+
### **🚀 LeetCode API Endpoints (with `/leetcode` prefix)**
6+
-**User Profiles**: `/leetcode/:username` - Get complete user profile
7+
-**User Badges**: `/leetcode/:username/badges` - Get user achievement badges
8+
-**Solved Problems**: `/leetcode/:username/solved` - Get statistics of solved problems
9+
-**Contest Info**: `/leetcode/:username/contest` - Get contest participation details
10+
-**Contest History**: `/leetcode/:username/contest/history` - Get contest history
11+
-**Submissions**: `/leetcode/:username/submission` - Get recent submissions with limit support
12+
-**Accepted Submissions**: `/leetcode/:username/acSubmission` - Get accepted submissions only
13+
-**Calendar**: `/leetcode/:username/calendar` - Get submission calendar data
14+
-**Full Profile**: `/leetcode/userProfile/:username` - Get complete profile in one call
15+
-**Language Stats**: `/leetcode/languageStats?username=name` - Get programming language statistics
16+
-**Skill Stats**: `/leetcode/skillStats/:username` - Get skill-based statistics
17+
-**Contest Ranking**: `/leetcode/userContestRankingInfo/:username` - Get contest ranking info
18+
19+
### **🍳 CodeChef API Endpoints (NEW!)**
20+
-**User Profile**: `/codechef/user/:username` - Get complete CodeChef profile
21+
-**User Rating**: `/codechef/user/:username/rating` - Get rating (returns 0 if no contests)
22+
-**User Ranking**: `/codechef/user/:username/ranking` - Get global and country ranking
23+
-**User Stats**: `/codechef/user/:username/stats` - Get comprehensive user statistics
24+
-**Contest List**: `/codechef/contests` - Get list of CodeChef contests
25+
26+
### **❓ LeetCode Problem Endpoints**
27+
-**Daily Question**: `/leetcode/daily` - Get today's daily challenge
28+
-**Raw Daily**: `/leetcode/dailyQuestion` - Get raw daily question data
29+
-**Problem Details**: `/leetcode/select?titleSlug=question-slug` - Get specific problem
30+
-**Problems List**: `/leetcode/problems` - Get paginated problems with filtering
31+
- Supports: `limit`, `skip`, `tags`, `difficulty` parameters
32+
- Example: `/leetcode/problems?difficulty=EASY&tags=array&limit=10`
33+
34+
### **💬 LeetCode Discussion Endpoints**
35+
-**Trending Discussions**: `/leetcode/trendingDiscuss?first=20` - Get trending discussions
36+
-**Discussion Topic**: `/leetcode/discussTopic/:topicId` - Get specific discussion
37+
-**Discussion Comments**: `/leetcode/discussComments/:topicId` - Get discussion comments
38+
39+
## 🔧 Key Features Implemented
40+
41+
### **🔍 Platform Differentiation**
42+
- **LeetCode APIs**: All prefixed with `/leetcode/` for clear separation
43+
- **CodeChef APIs**: All prefixed with `/codechef/` for clear identification
44+
- **Platform Field**: Each response includes `"platform": "LeetCode"` or `"platform": "CodeChef"`
45+
46+
### **🚫 Zero Rating Handling**
47+
- **CodeChef Rating**: Returns `0` when user hasn't participated in any contests
48+
- **Contest Count**: Returns `totalContests: 0` for users with no contest history
49+
- **Graceful Degradation**: API works even when user has minimal activity
50+
51+
### **🛡️ Robust Error Handling**
52+
- **User Validation**: Validates usernames (supports dots for CodeChef)
53+
- **404 Handling**: Proper error responses for non-existent users
54+
- **Rate Limiting**: 100 requests per 15 minutes per IP
55+
- **Timeout Protection**: 30-second timeouts for external API calls
56+
57+
### **📊 Response Format**
58+
```json
59+
{
60+
"success": true,
61+
"message": "Data retrieved successfully",
62+
"data": {
63+
"platform": "CodeChef|LeetCode",
64+
// ... platform-specific data
65+
},
66+
"timestamp": "2025-07-18T07:53:27.485Z"
67+
}
68+
```
69+
70+
## 🧪 Testing Results
71+
72+
### **✅ Working Endpoints** (Tested Successfully)
73+
- LeetCode user profiles, badges, solved stats
74+
- LeetCode daily questions and problems list
75+
- LeetCode trending discussions
76+
- CodeChef user profiles with zero rating handling
77+
- CodeChef rating, ranking, and statistics
78+
- Health check and API documentation
79+
80+
### **⚠️ Known Limitations**
81+
- Some LeetCode users may not have contest data
82+
- CodeChef contest list may be empty (API limitation)
83+
- CodeChef data depends on web scraping (may need updates if site changes)
84+
85+
## 🚀 How to Use
86+
87+
### **Start the Server**
88+
```bash
89+
npm start # Production
90+
npm run dev # Development with auto-reload
91+
npm run demo # Run comprehensive test
92+
```
93+
94+
### **Example API Calls**
95+
```bash
96+
# LeetCode user profile
97+
curl "http://localhost:3000/leetcode/leetcode"
98+
99+
# CodeChef user rating (returns 0 if no contests)
100+
curl "http://localhost:3000/codechef/user/admin/rating"
101+
102+
# LeetCode daily question
103+
curl "http://localhost:3000/leetcode/daily"
104+
105+
# LeetCode problems with filters
106+
curl "http://localhost:3000/leetcode/problems?difficulty=EASY&limit=5"
107+
108+
# CodeChef user statistics
109+
curl "http://localhost:3000/codechef/user/admin/stats"
110+
```
111+
112+
## 📈 Performance & Scalability
113+
114+
- **Concurrent Requests**: Handles multiple API calls efficiently
115+
- **Caching**: Response compression for better performance
116+
- **Security**: Helmet.js for security headers, CORS enabled
117+
- **Monitoring**: Comprehensive logging and error tracking
118+
119+
## 🎯 Mission Accomplished!
120+
121+
**All requested LeetCode endpoints implemented**
122+
**CodeChef integration with zero rating handling**
123+
**Clear platform differentiation with prefixes**
124+
**Robust error handling and validation**
125+
**Comprehensive testing and documentation**
126+
**Production-ready with security features**
127+
128+
The API successfully differentiates between LeetCode and CodeChef, handles users with no contest history (returning 0 ratings), and provides a comprehensive set of endpoints for both platforms! 🎉

README.md

Lines changed: 196 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,196 @@
1+
# LeetCode & CodeChef API 🚀
2+
3+
A comprehensive REST API that provides access to both LeetCode and CodeChef data. Get user profiles, problem details, contest information, ratings, and more from both platforms!
4+
5+
## Features
6+
7+
- **LeetCode Data**: User profiles, badges, solved problems, contest history, submissions
8+
- **CodeChef Data**: User profiles, ratings, rankings, contest statistics (returns 0 if no contests)
9+
- **Problem Data**: Daily questions, problem lists with filtering, detailed problem info
10+
- **Discussion Data**: Trending discussions, topics, and comments
11+
- **Advanced Features**: Rate limiting, error handling, CORS support, compression
12+
13+
## Quick Start
14+
15+
### Installation
16+
17+
```bash
18+
# Clone the repository
19+
git clone <your-repo-url>
20+
cd leetcode-api
21+
22+
# Install dependencies
23+
npm install
24+
25+
# Start the server
26+
npm start
27+
28+
# For development with auto-reload
29+
npm run dev
30+
```
31+
32+
### Usage
33+
34+
The API will be available at `http://localhost:3000`
35+
36+
## API Endpoints
37+
38+
### 👤 User Endpoints
39+
40+
| Endpoint | Description | Example |
41+
|----------|-------------|---------|
42+
| `/:username` | Get user profile details | `/john_doe` |
43+
| `/:username/badges` | Get user badges | `/john_doe/badges` |
44+
| `/:username/solved` | Get solved problems statistics | `/john_doe/solved` |
45+
| `/:username/contest` | Get contest participation details | `/john_doe/contest` |
46+
| `/:username/contest/history` | Get contest history | `/john_doe/contest/history` |
47+
| `/:username/submission` | Get recent submissions (last 20) | `/john_doe/submission` |
48+
| `/:username/submission?limit=10` | Get limited submissions | `/john_doe/submission?limit=10` |
49+
| `/:username/acSubmission` | Get accepted submissions | `/john_doe/acSubmission` |
50+
| `/:username/acSubmission?limit=7` | Get limited accepted submissions | `/john_doe/acSubmission?limit=7` |
51+
| `/:username/calendar` | Get submission calendar | `/john_doe/calendar` |
52+
53+
### 😀 New User Endpoints
54+
55+
| Endpoint | Description | Example |
56+
|----------|-------------|---------|
57+
| `/userProfile/:username` | Get full profile in one call | `/userProfile/john_doe` |
58+
| `/userProfileCalendar?username=name&year=2024` | Get calendar with year | `/userProfileCalendar?username=john_doe&year=2024` |
59+
| `/languageStats?username=name` | Get language statistics | `/languageStats?username=john_doe` |
60+
| `/userProfileUserQuestionProgressV2/:userSlug` | Get question progress | `/userProfileUserQuestionProgressV2/john_doe` |
61+
| `/skillStats/:username` | Get skill statistics | `/skillStats/john_doe` |
62+
| `/userContestRankingInfo/:username` | Get contest ranking | `/userContestRankingInfo/john_doe` |
63+
64+
### ❓ Problem Endpoints
65+
66+
| Endpoint | Description | Example |
67+
|----------|-------------|---------|
68+
| `/daily` | Get daily challenge question | `/daily` |
69+
| `/dailyQuestion` | Get raw daily question data | `/dailyQuestion` |
70+
| `/select?titleSlug=question-slug` | Get specific question details | `/select?titleSlug=two-sum` |
71+
| `/problems` | Get problems list (20 by default) | `/problems` |
72+
| `/problems?limit=10` | Get limited number of problems | `/problems?limit=10` |
73+
| `/problems?tags=array+string` | Filter problems by tags | `/problems?tags=array+string` |
74+
| `/problems?difficulty=EASY` | Filter by difficulty (EASY/MEDIUM/HARD) | `/problems?difficulty=EASY` |
75+
| `/problems?skip=20` | Skip first N problems | `/problems?skip=20` |
76+
| `/problems?tags=array&limit=10&skip=5` | Combined filters | `/problems?tags=array&limit=10&skip=5` |
77+
78+
### 💬 Discussion Endpoints
79+
80+
| Endpoint | Description | Example |
81+
|----------|-------------|---------|
82+
| `/trendingDiscuss?first=20` | Get trending discussions | `/trendingDiscuss?first=10` |
83+
| `/discussTopic/:topicId` | Get discussion topic | `/discussTopic/12345` |
84+
| `/discussComments/:topicId` | Get discussion comments | `/discussComments/12345` |
85+
86+
## Response Format
87+
88+
All endpoints return data in a consistent format:
89+
90+
```json
91+
{
92+
"success": true,
93+
"message": "Data retrieved successfully",
94+
"data": { ... },
95+
"timestamp": "2024-01-01T12:00:00.000Z"
96+
}
97+
```
98+
99+
### Error Response
100+
101+
```json
102+
{
103+
"success": false,
104+
"message": "Error description",
105+
"timestamp": "2024-01-01T12:00:00.000Z"
106+
}
107+
```
108+
109+
## Query Parameters
110+
111+
### Problems Endpoint
112+
113+
- `limit`: Number of problems to return (max 100, default 20)
114+
- `skip`: Number of problems to skip (default 0)
115+
- `tags`: Filter by tags (use + to separate multiple tags)
116+
- `difficulty`: Filter by difficulty (EASY, MEDIUM, HARD)
117+
118+
### Example Queries
119+
120+
```bash
121+
# Get user profile
122+
curl http://localhost:3000/john_doe
123+
124+
# Get daily question
125+
curl http://localhost:3000/daily
126+
127+
# Get 10 easy array problems
128+
curl "http://localhost:3000/problems?difficulty=EASY&tags=array&limit=10"
129+
130+
# Get trending discussions
131+
curl "http://localhost:3000/trendingDiscuss?first=5"
132+
```
133+
134+
## Rate Limiting
135+
136+
- 100 requests per 15 minutes per IP address
137+
- Rate limit headers included in responses:
138+
- `X-RateLimit-Limit`: Request limit
139+
- `X-RateLimit-Remaining`: Remaining requests
140+
- `X-RateLimit-Reset`: Reset time
141+
142+
## Environment Variables
143+
144+
Create a `.env` file for configuration:
145+
146+
```env
147+
PORT=3000
148+
NODE_ENV=development
149+
```
150+
151+
## Error Handling
152+
153+
The API includes comprehensive error handling for:
154+
- Invalid usernames
155+
- Non-existent users
156+
- Malformed requests
157+
- Rate limiting
158+
- Network errors
159+
- GraphQL errors
160+
161+
## Technologies Used
162+
163+
- **Node.js** - Runtime environment
164+
- **Express.js** - Web framework
165+
- **Axios** - HTTP client for GraphQL requests
166+
- **CORS** - Cross-origin resource sharing
167+
- **Helmet** - Security headers
168+
- **Compression** - Response compression
169+
170+
## Contributing
171+
172+
1. Fork the repository
173+
2. Create a feature branch
174+
3. Make your changes
175+
4. Add tests if applicable
176+
5. Submit a pull request
177+
178+
## License
179+
180+
MIT License - see LICENSE file for details
181+
182+
## Support
183+
184+
For issues and questions:
185+
- Create an issue on GitHub
186+
- Check the API documentation at `http://localhost:3000/`
187+
- Verify your requests match the expected format
188+
189+
## Changelog
190+
191+
### v1.0.0
192+
- Initial release with all LeetCode API endpoints
193+
- User profile and statistics
194+
- Problem data and daily questions
195+
- Discussion and trending topics
196+
- Rate limiting and error handling

0 commit comments

Comments
 (0)