Skip to content

TypeScript NestJS Backend API โ€‹

HaloLight NestJS backend API is built on NestJS 11, providing enterprise-grade backend services with complete RBAC permission system.

API Documentation: https://halolight-api-nestjs.h7ml.cn/docs

GitHub: https://github.com/halolight/halolight-api-nestjs

Features โ€‹

  • ๐Ÿ” JWT Dual Tokens - Access Token + Refresh Token with auto-renewal
  • ๐Ÿ›ก๏ธ RBAC Permissions - Role-Based Access Control with wildcard matching
  • ๐Ÿ“ก RESTful API - Standardized interface design with OpenAPI documentation
  • ๐Ÿ—„๏ธ Prisma ORM - Type-safe database operations
  • โœ… Data Validation - Request parameter validation and error handling
  • ๐Ÿ“Š Logging System - Request logs and error tracking
  • ๐Ÿณ Docker Support - Containerized deployment

Tech Stack โ€‹

TechnologyVersionDescription
TypeScript5.7Runtime
NestJS11Web Framework
Prisma5Database ORM
PostgreSQL16Data Storage
class-validator-Data Validation
JWT-Authentication
Swagger-API Documentation

Quick Start โ€‹

Requirements โ€‹

  • Node.js >= 18
  • pnpm >= 8
  • PostgreSQL (optional, defaults to SQLite)

Installation โ€‹

bash
# Clone repository
git clone https://github.com/halolight/halolight-api-nestjs.git
cd halolight-api-nestjs

# Install dependencies
pnpm install

Environment Variables โ€‹

bash
cp .env.example .env
env
# Database
DATABASE_URL=postgresql://user:password@localhost:5432/halolight_db

# JWT Keys
JWT_SECRET=your-super-secret-key
JWT_ACCESS_EXPIRES=15m
JWT_REFRESH_EXPIRES=7d

# Service Configuration
PORT=3000
NODE_ENV=development

Database Initialization โ€‹

bash
pnpm prisma:generate
pnpm prisma:migrate
pnpm prisma:seed

Start Service โ€‹

bash
# Development mode
pnpm dev

# Production mode
pnpm build
pnpm start:prod

Visit http://localhost:3000

Project Structure โ€‹

halolight-api-nestjs/
โ”œโ”€โ”€ src/
โ”‚   โ”œโ”€โ”€ common/                  # Shared modules
โ”‚   โ”œโ”€โ”€ configs/                 # Configuration modules
โ”‚   โ”œโ”€โ”€ infrastructure/          # Infrastructure layer
โ”‚   โ”œโ”€โ”€ modules/                 # Business modules (12 modules)
โ”‚   โ”‚   โ”œโ”€โ”€ auth/                # Authentication
โ”‚   โ”‚   โ”œโ”€โ”€ users/               # User management
โ”‚   โ”‚   โ”œโ”€โ”€ roles/               # Role management
โ”‚   โ”‚   โ”œโ”€โ”€ permissions/         # Permission management
โ”‚   โ”‚   โ”œโ”€โ”€ teams/               # Team management
โ”‚   โ”‚   โ”œโ”€โ”€ documents/           # Document management
โ”‚   โ”‚   โ”œโ”€โ”€ files/               # File management
โ”‚   โ”‚   โ”œโ”€โ”€ folders/             # Folder management
โ”‚   โ”‚   โ”œโ”€โ”€ calendar/            # Calendar management
โ”‚   โ”‚   โ”œโ”€โ”€ notifications/       # Notification management
โ”‚   โ”‚   โ”œโ”€โ”€ messages/            # Message management
โ”‚   โ”‚   โ””โ”€โ”€ dashboard/           # Dashboard statistics
โ”‚   โ”œโ”€โ”€ app.controller.ts        # Root controller
โ”‚   โ”œโ”€โ”€ app.service.ts           # Root service
โ”‚   โ”œโ”€โ”€ app.module.ts            # Root module
โ”‚   โ””โ”€โ”€ main.ts                  # Application entry
โ”œโ”€โ”€ prisma/
โ”‚   โ”œโ”€โ”€ schema.prisma            # Database model definitions
โ”‚   โ””โ”€โ”€ migrations/              # Database migration history
โ”œโ”€โ”€ test/                        # Test files
โ”œโ”€โ”€ Dockerfile                   # Docker configuration
โ”œโ”€โ”€ docker-compose.yml
โ””โ”€โ”€ package.json

API Modules โ€‹

Authentication Endpoints โ€‹

MethodPathDescriptionPermission
POST/api/auth/loginUser loginPublic
POST/api/auth/registerUser registrationPublic
POST/api/auth/refreshRefresh tokenPublic
POST/api/auth/logoutUser logoutRequired
POST/api/auth/forgot-passwordForgot passwordPublic
POST/api/auth/reset-passwordReset passwordPublic

User Management Endpoints โ€‹

MethodPathDescriptionPermission
GET/api/usersGet user listusers:view
GET/api/users/:idGet user detailsusers:view
POST/api/usersCreate userusers:create
PUT/api/users/:idUpdate userusers:update
DELETE/api/users/:idDelete userusers:delete
GET/api/users/meGet current userRequired

Complete Endpoint List โ€‹

Document Management (Documents) - 11 endpoints โ€‹

MethodPathDescription
GET/api/documentsGet document list
GET/api/documents/:idGet document details
POST/api/documentsCreate document
PUT/api/documents/:idUpdate document
DELETE/api/documents/:idDelete document

File Management (Files) - 14 endpoints โ€‹

MethodPathDescription
GET/api/filesGet file list
GET/api/files/:idGet file details
POST/api/files/uploadUpload file
PUT/api/files/:idUpdate file info
DELETE/api/files/:idDelete file

Message Management (Messages) - 5 endpoints โ€‹

MethodPathDescription
GET/api/messagesGet message list
GET/api/messages/:idGet message details
POST/api/messagesSend message
PUT/api/messages/:id/readMark as read
DELETE/api/messages/:idDelete message

Notification Management (Notifications) - 5 endpoints โ€‹

MethodPathDescription
GET/api/notificationsGet notification list
PUT/api/notifications/:id/readMark as read
PUT/api/notifications/read-allMark all as read
DELETE/api/notifications/:idDelete notification

Calendar Management (Calendar) - 9 endpoints โ€‹

MethodPathDescription
GET/api/calendar/eventsGet event list
GET/api/calendar/events/:idGet event details
POST/api/calendar/eventsCreate event
PUT/api/calendar/events/:idUpdate event
DELETE/api/calendar/events/:idDelete event

Dashboard (Dashboard) - 9 endpoints โ€‹

MethodPathDescription
GET/api/dashboard/statsStatistics data
GET/api/dashboard/visitsVisit trends
GET/api/dashboard/salesSales data
GET/api/dashboard/piePie chart data
GET/api/dashboard/tasksTask list
GET/api/dashboard/overviewSystem overview

Authentication Mechanism โ€‹

JWT Dual Tokens โ€‹

Access Token:  15 minutes validity, used for API requests
Refresh Token: 7 days validity, used to refresh Access Token

Request Headers โ€‹

http
Authorization: Bearer <access_token>

Refresh Flow โ€‹

typescript
// Token refresh example
const response = await fetch('/api/auth/refresh', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ refreshToken })
});

const { accessToken, refreshToken: newRefreshToken } = await response.json();

Permission System โ€‹

Role Definitions โ€‹

RoleDescriptionPermissions
super_adminSuper Administrator* (all permissions)
adminAdministratorusers:*, documents:*, ...
userRegular Userdocuments:view, files:view, ...
guestGuestdashboard:view

Permission Format โ€‹

{resource}:{action}

Examples:
- users:view      # View users
- users:create    # Create users
- users:*         # All user operations
- *               # All permissions

Error Handling โ€‹

Error Response Format โ€‹

json
{
  "success": false,
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Request validation failed",
    "details": [
      { "field": "email", "message": "Invalid email format" }
    ]
  }
}

Error Codes โ€‹

Status CodeError CodeDescription
400VALIDATION_ERRORValidation failed
401UNAUTHORIZEDUnauthorized
403FORBIDDENNo permission
404NOT_FOUNDResource not found
409CONFLICTResource conflict
500INTERNAL_ERRORServer error

Common Commands โ€‹

bash
# Development
pnpm dev              # Start development server
pnpm start:debug      # Debug mode

# Build
pnpm build            # Build for production
pnpm start:prod       # Run production build

# Testing
pnpm test             # Run unit tests
pnpm test:e2e         # Run E2E tests
pnpm test:cov         # Generate coverage report

# Database
pnpm prisma:generate  # Generate Prisma Client
pnpm prisma:migrate   # Run migrations
pnpm prisma:studio    # Prisma Studio GUI
pnpm prisma:seed      # Run seed data

# Code Quality
pnpm lint             # ESLint check
pnpm lint:fix         # Auto-fix issues
pnpm format           # Prettier formatting

Deployment โ€‹

Docker โ€‹

bash
docker build -t halolight-api-nestjs .
docker run -p 3000:3000 halolight-api-nestjs

Docker Compose โ€‹

bash
docker-compose up -d
yaml
# docker-compose.yml
version: '3.8'

services:
  app:
    build: .
    ports:
      - "3000:3000"
    environment:
      - NODE_ENV=production
      - DATABASE_URL=${DATABASE_URL}
      - JWT_SECRET=${JWT_SECRET}
    restart: unless-stopped

  db:
    image: postgres:16-alpine
    environment:
      POSTGRES_DB: halolight
      POSTGRES_USER: ${DB_USER}
      POSTGRES_PASSWORD: ${DB_PASSWORD}
    volumes:
      - postgres_data:/var/lib/postgresql/data

volumes:
  postgres_data:

Production Configuration โ€‹

env
NODE_ENV=production
DATABASE_URL=postgresql://user:pass@host:5432/db
JWT_SECRET=your-production-secret

Testing โ€‹

Run Tests โ€‹

bash
pnpm test             # Unit tests
pnpm test:e2e         # E2E tests
pnpm test:cov         # Coverage report

Test Example โ€‹

typescript
describe('AuthController', () => {
  it('should login user', async () => {
    const response = await request(app.getHttpServer())
      .post('/api/auth/login')
      .send({ email: 'test@example.com', password: 'password' })
      .expect(200);

    expect(response.body).toHaveProperty('accessToken');
  });
});

Performance Metrics โ€‹

Benchmarks โ€‹

MetricValueConditions
Request Throughput5000+ QPSSingle CPU core
Average Response Time<50msSimple queries
Memory Usage~150MBAfter startup
CPU Usage<30%Normal load

Observability โ€‹

Logging System โ€‹

typescript
// Logging configuration
import { WinstonModule } from 'nest-winston';

WinstonModule.forRoot({
  transports: [
    new winston.transports.File({ filename: 'error.log', level: 'error' }),
    new winston.transports.File({ filename: 'combined.log' })
  ]
});

Health Check โ€‹

typescript
// GET /health
{
  "status": "ok",
  "info": {
    "database": { "status": "up" },
    "redis": { "status": "up" }
  }
}

Monitoring Metrics โ€‹

typescript
// Prometheus metrics endpoint
// GET /metrics
http_requests_total{method="GET",status="200"} 1234
http_request_duration_seconds{quantile="0.99"} 0.052

FAQ โ€‹

Q: How to configure database connection? โ€‹

A: Set DATABASE_URL in .env file

env
DATABASE_URL="postgresql://user:password@localhost:5432/halolight"

Q: How to handle file uploads? โ€‹

A: Use FileInterceptor from @nestjs/platform-express

typescript
@Post('upload')
@UseInterceptors(FileInterceptor('file'))
uploadFile(@UploadedFile() file: Express.Multer.File) {
  return { filename: file.originalname };
}

Development Tools โ€‹

  • Prisma Studio - Database visualization and management
  • Swagger UI - API documentation and testing
  • Postman - API debugging tool
  • NestJS CLI - Code generation tool

Backend Comparison โ€‹

FeatureNestJSFastAPISpring BootLaravel
LanguageTypeScriptPythonJavaPHP
ORMPrismaSQLAlchemyJPAEloquent
Performanceโญโญโญโญโญโญโญโญโญโญโญโญโญโญ
Learning Curveโญโญโญโญโญโญโญโญโญโญโญโญโญ