# expense-tracker-fastify-api **Repository Path**: linjunbin0101/expense-tracker-fastify-api ## Basic Information - **Project Name**: expense-tracker-fastify-api - **Description**: No description available - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2025-12-25 - **Last Updated**: 2026-01-09 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # Expense Tracker Fastify API A high-performance Fastify-based backend API for expense tracking applications. This framework provides a robust and scalable solution for managing personal or business expenses with features like transaction management, category tracking, and user authentication. ## Core Features - **Fastify Server**: High-performance Node.js web framework with low overhead - **Hot Reload Support**: Auto-restart server during development for faster iteration - **Auto Load Mechanism**: Auto-load plugins and routes for simplified development - **Health Check Endpoint**: `/health` route for system status monitoring - **MongoDB Integration**: Mongoose ORM for seamless database operations - **Unified Response Format**: Consistent API response structure across all endpoints - **Batch Processing**: Optimized batch operations for efficient transaction management - **CSV Export/Import**: Support for exporting and importing transactions as CSV files - **Structured Logging**: Multi-level logging system with detailed request/response information - **API Versioning**: URL-based API versioning support - **Rate Limiting**: Built-in protection against API abuse and DDoS attacks - **Input Validation**: Strict JSON Schema validation for all input parameters - **Security Features**: Protection against common vulnerabilities (XSS, SQL injection, etc.) - **Activity Logging**: Comprehensive user behavior tracking for audit and debugging - **JWT Authentication**: Secure token-based authentication with refresh token support - **Swagger Documentation**: Interactive API documentation with Swagger UI ## Installation ### Prerequisites - Node.js 18+ or compatible version - MongoDB 5+ or MongoDB Atlas account - npm or yarn package manager ### Setup 1. **Clone the repository**: ```bash git clone cd expense-tracker-fastify-api ``` 2. **Install dependencies**: ```bash npm install ``` 3. **Configure environment variables**: Create a `.env` file in the root directory with the following content: ```env # Server Configuration PORT=3000 HOST=0.0.0.0 NODE_ENV=development LOG_LEVEL=debug # Database Configuration MONGO_URI=mongodb://localhost:27017/expense-tracker # JWT Configuration JWT_SECRET=your-strong-jwt-secret-change-me-in-production ACCESS_TOKEN_EXPIRE=15m REFRESH_TOKEN_EXPIRE=7d # CORS Configuration CORS_ORIGIN=http://localhost:3001 # Rate Limiting Configuration RATE_LIMIT_MAX=100 RATE_LIMIT_TIME_WINDOW=1 minute # File Upload Configuration MAX_FILE_SIZE=10485760 MAX_FILES=1 # HTTPS Configuration (optional, for production) # HTTPS_ENABLED=true # HTTPS_KEY=/path/to/key.pem # HTTPS_CERT=/path/to/cert.pem ``` 4. **Start the server**: - Development mode (with hot reload): ```bash npm run dev ``` - Production mode: ```bash npm run start ``` ## Development Tools - **ESLint Configuration**: 4 spaces indentation, single quotes, mandatory semicolons - **Development Scripts**: - `npm run start`: Start production server - `npm run dev`: Start development server with hot reload - `npm run lint`: Run ESLint check - `npm run lint:fix`: Auto fix ESLint issues - `npm run test`: Run tests - `npm run test:watch`: Run tests in watch mode - `npm run test:coverage`: Run tests with coverage report ## API Documentation ### Swagger UI The API is fully documented using Swagger. Access the interactive documentation at: ```text http://localhost:3000/docs ``` ### Authentication All protected endpoints require a JWT token in the `Authorization` header: ```text Authorization: Bearer ``` ### Response Format All API endpoints return a unified response format: ```json { "code": 0, "timestamp": 1234567890, "result": { "message": "Success message", "data": {} } } ``` ## Usage Examples ### 1. User Authentication #### Login ```bash curl -X POST http://localhost:3000/auth/login \ -H "Content-Type: application/json" \ -d '{"phone": "13800138000", "password": "your-password"}' ``` **Response**: ```json { "code": 0, "timestamp": 1704067200000, "result": { "user": { "_id": "658d1e2f1a2b3c4d5e6f7a8b", "phone": "13800138000", "role": "user", "email": "user@example.com", "nickname": "User1", "avatar": "", "createdAt": "2023-12-25T00:00:00.000Z", "updatedAt": "2023-12-25T00:00:00.000Z" }, "accessToken": { "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", "expiresIn": 900 }, "refreshToken": { "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", "expiresIn": 604800 } } } ``` ### 2. Create a Transaction ```bash curl -X POST http://localhost:3000/transactions \ -H "Content-Type: application/json" \ -H "Authorization: Bearer " \ -d '{ "amount": 100.50, "category": "Food", "subcategory": "Dining", "description": "Lunch at restaurant", "date": "2023-12-25T12:00:00Z", "type": "expense", "tags": ["food", "lunch"] }' ``` ### 3. Get Transactions with Filters ```bash curl -X GET "http://localhost:3000/transactions?category=Food&startDate=2023-12-01&endDate=2023-12-31" \ -H "Authorization: Bearer " ``` ## Project Structure ```bash expense-tracker-fastify-api/ ├── app.js # Main entry file ├── config/ # Configuration files │ └── index.js # Centralized configuration ├── models/ # Mongoose models ├── plugins/ # Plugins directory (auto loaded) ├── routes/ # Routes directory (auto loaded) │ ├── auth.js # Authentication routes │ ├── categories.js # Category management routes │ ├── health.js # Health check route │ ├── transactions.js # Transaction management routes │ ├── users.js # User management routes ├── scripts/ # Scripts directory │ ├── clearDatabase.js # Clear database script │ ├── seedData.js # Seed data script ├── services/ # Business logic services │ ├── authService.js # Authentication service │ ├── transactionService.js # Transaction management service │ └── userService.js # User management service ├── utils/ # Utility functions ├── .env # Environment variables ├── .gitignore # Git ignore file ├── eslint.config.mjs # ESLint configuration ├── package-lock.json # NPM lock file ├── package.json # Project configuration └── README.md # Project documentation ``` ## Start Server ```bash # Development mode (hot reload) npm run dev # Production mode npm run start ``` ## Access Endpoints ### Authentication Endpoints - User login: `POST http://localhost:1225/auth/login` - Refresh token: `POST http://localhost:1225/auth/refresh-token` - Logout: `POST http://localhost:1225/auth/logout` - Logout all devices: `POST http://localhost:1225/auth/logout-all` ### User Management Endpoints - User register: `POST http://localhost:1225/users/register` - Get current user: `GET http://localhost:1225/users/me` - Update user info: `PUT http://localhost:1225/users/me` - Update password: `PUT http://localhost:1225/users/me/password` - Delete user: `DELETE http://localhost:1225/users/me` - Get all users: `GET http://localhost:1225/users` (admin/superadmin only) ### Category Management Endpoints - Get all categories: `GET http://localhost:1225/categories` - Get single category: `GET http://localhost:1225/categories/:id` - Create category: `POST http://localhost:1225/categories` (admin/superadmin only) - Update category: `PUT http://localhost:1225/categories/:id` (admin/superadmin only) - Delete category: `DELETE http://localhost:1225/categories/:id` (admin/superadmin only) ### Transaction Management Endpoints - Create transaction: `POST http://localhost:1225/transactions` - Get all transactions: `GET http://localhost:1225/transactions` - Get single transaction: `GET http://localhost:1225/transactions/:id` - Update transaction: `PUT http://localhost:1225/transactions/:id` - Delete transaction: `DELETE http://localhost:1225/transactions/:id` - Batch update transactions: `PUT http://localhost:1225/transactions/batch` - Batch delete transactions: `DELETE http://localhost:1225/transactions/batch` - Export transactions as CSV: `GET http://localhost:1225/transactions/export` - Import transactions from CSV: `POST http://localhost:1225/transactions/import` - Get transaction statistics: `GET http://localhost:1225/transactions/statistics` - Get transaction summary (multi-dimensional): `GET http://localhost:1225/transactions/summary` ### System Endpoints - Health check: `http://localhost:1225/health` ## Auto Update Note This README.md file will be automatically updated to record the latest state and features of the project.