A comprehensive, production-ready backend API for property management operations built with Node.js, Express, Prisma ORM, and PostgreSQL.
This API follows Clean Architecture principles with strict separation of concerns:
- π Interface Layer: Controllers, Routes, DTOs, Middlewares
- π§ Business Logic Layer: Services (no business logic in controllers)
- πΎ Data Access Layer: Repositories (using Repository pattern)
- π‘οΈ Cross-cutting Concerns: Authentication, Authorization, Validation, Logging, Error Handling
- β JWT Authentication with Access + Refresh token strategy
- β Role-based Authorization (Admin, Landlord, Tenant)
- β Dependency Injection pattern
- β Repository Pattern for database abstraction
- β Centralized Error Handling with consistent responses
- β Global Response Formatter for API consistency
- β Production-ready Logging (Winston)
- β Environment-based Configuration with validation
- β Request Validation (Joi schemas)
- β Rate Limiting and Security middleware
- β Health Check endpoints
- β Graceful Shutdown handling
- Node.js 18.0.0 or higher
- PostgreSQL 12.0 or higher
- npm or yarn
# Clone the repository
git clone <repository-url>
cd property-management-api
# Install dependencies
npm install
# Install Prisma CLI globally (optional)
npm install -g prisma# Copy environment template
cp .env.example .env
# Edit .env file with your configuration
nano .envRequired Environment Variables:
DATABASE_URL="postgresql://username:password@localhost:5432/property_management"
JWT_SECRET="your-super-secure-jwt-secret-minimum-32-characters"
JWT_REFRESH_SECRET="your-refresh-secret-minimum-32-characters"# Generate Prisma client
npx prisma generate
# Run database migrations
npx prisma migrate dev --name init
# (Optional) Seed database with sample data
npm run prisma:seed
# (Optional) Open Prisma Studio to view data
npm run prisma:studio# Development mode with auto-restart
npm run dev
# Production mode
npm startThe API will be available at http://localhost:3000
src/
βββ app.js # Express app configuration
βββ server.js # Server entry point with graceful shutdown
βββπ config/
β βββ index.js # Environment-based configuration
β βββ database.js # Prisma client setup
βββ π middlewares/
β βββ auth.js # Authentication & authorization
β βββ errorHandler.js # Global error handling
β βββ responseFormatter.js # Response formatting
βββ π utils/
β βββ apiResponse.js # Response helpers
β βββ jwt.js # JWT utilities
β βββ logger.js # Winston logger setup
βββ π validators/
β βββ auth.validator.js # Authentication validation schemas
β βββ common.validator.js # Reusable validation patterns
βββ π routes/
β βββ index.js # Main API routes consolidation
βββ π modules/
βββ π auth/ # Authentication module
β βββ auth.controller.js
β βββ auth.dto.js
β βββ auth.repository.js
β βββ auth.routes.js
β βββ auth.service.js
β βββ auth.test.http
βββ π user/ # User management module
βββ user.controller.js
βββ user.dto.js
βββ user.repository.js
βββ user.routes.js
βββ user.service.js
βββ user.test.http
| Method | Endpoint | Description | Access |
|---|---|---|---|
POST |
/register |
Register new user | Public |
POST |
/login |
User login | Public |
POST |
/refresh |
Refresh access token | Public |
POST |
/logout |
User logout | Private |
GET |
/me |
Get current user | Private |
GET |
/profile |
Get user profile | Private |
PUT |
/profile |
Update profile | Private |
POST |
/change-password |
Change password | Private |
DELETE |
/account |
Delete account | Private |
GET |
/stats |
User statistics | Admin |
| Method | Endpoint | Description | Access |
|---|---|---|---|
GET |
/ |
List users with pagination | Admin |
GET |
/search |
Search users | Admin |
GET |
/role/:role |
Get users by role | Admin |
POST |
/ |
Create new user | Admin |
GET |
/:id |
Get user details | Admin |
PUT |
/:id |
Update user | Admin |
DELETE |
/:id |
Delete user | Admin |
POST |
/bulk-action |
Bulk operations | Admin |
GET |
/me/dashboard |
Current user dashboard | Private |
GET |
/:id/analytics |
User analytics | Admin/Own |
The following modules follow the same pattern and can be implemented:
- Properties (
/api/v1/properties) - Property management - Tenancies (
/api/v1/tenancies) - Tenancy relationships - Maintenance (
/api/v1/maintenance) - Maintenance requests - Documents (
/api/v1/documents) - Document management - Conversations (
/api/v1/conversations) - Messaging system - Payments (
/api/v1/payments) - Rent payment tracking - Reports (
/api/v1/reports) - Analytics and reporting
# 1. Register new user
POST /api/v1/auth/register
{
"name": "John Doe",
"email": "john@example.com",
"password": "SecurePassword123!",
"role": "LANDLORD"
}
# 2. Login to get tokens
POST /api/v1/auth/login
{
"email": "john@example.com",
"password": "SecurePassword123!"
}
# Response includes access + refresh tokens
{
"success": true,
"data": {
"user": {...},
"tokens": {
"accessToken": "eyJ...",
"refreshToken": "eyJ...",
"tokenType": "Bearer",
"expiresIn": "15m"
}
}
}# Include Bearer token in Authorization header
curl -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
http://localhost:3000/api/v1/auth/profile# When access token expires, use refresh token
POST /api/v1/auth/refresh
{
"refreshToken": "YOUR_REFRESH_TOKEN"
}- Full CRUD access to all resources
- User management capabilities
- System statistics and reporting
- Audit log access
- Manage their own properties
- View associated tenants and tenancies
- Access property documents and maintenance
- Communicate with tenants and admin
- View their current property details
- Submit maintenance requests
- Access lease documents and statements
- Make rent payments and view history
- Communicate with landlord and admin
Each module includes .test.http files for manual API testing with VS Code REST Client extension:
src/modules/auth/auth.test.http- Authentication endpointssrc/modules/user/user.test.http- User management endpoints
### Login as admin
POST http://localhost:3000/api/v1/auth/login
Content-Type: application/json
{
"email": "admin@mccannandcurran.ie",
"password": "AdminPassword123!"
}
### Get all users (requires admin token)
GET http://localhost:3000/api/v1/users?page=1&limit=10
Authorization: Bearer {{accessToken}}All API responses follow a consistent structure:
{
"success": true,
"message": "Operation completed successfully",
"statusCode": 200,
"timestamp": "2024-03-02T10:30:00.000Z",
"data": { ... },
"meta": {
"pagination": { ... }
}
}{
"success": false,
"message": "Error description",
"statusCode": 400,
"timestamp": "2024-03-02T10:30:00.000Z",
"errors": [
{
"field": "email",
"message": "Invalid email format",
"value": "invalid-email"
}
]
}- π JWT Authentication with secure token generation
- π‘οΈ Password Hashing using bcrypt with configurable rounds
- π« Rate Limiting to prevent abuse
- π Input Validation with Joi schemas
- π‘οΈ Helmet.js security headers
- π CORS configuration for cross-origin requests
- π Audit Logging for security events
- β‘ Graceful Error Handling without information leakage
Ensure these are set in production:
NODE_ENV=production
DATABASE_URL="postgresql://..."
JWT_SECRET="long-secure-random-string"
JWT_REFRESH_SECRET="another-long-secure-random-string"
ALLOWED_ORIGINS="https://yourdomain.com"
LOG_LEVEL=warn# Deploy database changes
npx prisma migrate deploy
# Generate Prisma client
npx prisma generateUse PM2 or similar for process management:
# Install PM2
npm install -g pm2
# Start application
pm2 start src/server.js --name "property-api"
# Monitor
pm2 monit
# View logs
pm2 logs property-apiMonitor application health:
GET /health- Basic health checkGET /api/v1/health- Detailed API healthGET /api/v1/docs- API documentation
The API uses centralized error handling with:
const { AppError } = require('./middlewares/errorHandler');
// Throw operational errors
throw new AppError('Resource not found', 404);
throw new AppError('Validation failed', 422, validationErrors);- Prisma Errors - Database constraint violations, not found errors
- JWT Errors - Token validation and expiration
- Validation Errors - Joi schema validation failures
- File Upload Errors - Multer file size and type errors
Production-ready logging with Winston:
- Development: Colorized console output with stack traces
- Production: JSON format with file rotation
- Audit Logging: User actions and security events
- Request Logging: HTTP request/response logging
Log files (production):
logs/error.log- Error level logslogs/combined.log- All logs
- Follow the existing folder structure and patterns
- Each new module should include: DTO, Repository, Service, Controller, Routes, Tests
- Use TypeScript-style JSDoc comments for better documentation
- Add appropriate validation schemas
- Include comprehensive error handling
- Add audit logging for sensitive operations
For questions and support:
- Email: support@mccannandcurran.ie
- Documentation: Check the
src/modules/*/test.httpfiles for API examples
McCann & Curran Property Management Platform - Built with β€οΈ using Node.js, Express, Prisma, and PostgreSQL# rpr2011_2500_api