Skip to content

Bun Hono Backend API โ€‹

HaloLight Bun Backend API is built on Bun + Hono + Drizzle ORM, providing ultra-high-performance backend service.

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

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

Features โ€‹

  • ๐Ÿ” JWT Dual Token - Access Token + Refresh Token, automatic renewal
  • ๐Ÿ›ก๏ธ RBAC Authorization - Role-based access control with wildcard matching
  • ๐Ÿ“ก RESTful API - Standardized interface design, OpenAPI documentation
  • ๐Ÿ—„๏ธ Drizzle ORM - Type-safe database operations
  • โœ… Data Validation - Request parameter validation, error handling
  • ๐Ÿ“Š Logging System - Request logging, error tracking
  • ๐Ÿณ Docker Support - Containerized deployment
  • โšก Extreme Performance - 4x faster than Node.js

Tech Stack โ€‹

TechnologyVersionDescription
Bun1.1+Runtime
Hono4.xWeb Framework
Drizzle ORM0.36+Database ORM
PostgreSQL15+Data Storage
Zod3.xData Validation
JWT-Authentication
Swagger-API Documentation

Quick Start โ€‹

Requirements โ€‹

  • Bun >= 1.1
  • pnpm >= 8.0
  • PostgreSQL (optional, defaults to SQLite)

Installation โ€‹

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

# Install dependencies
pnpm install

Environment Variables โ€‹

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

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

# Service Config
PORT=3002
NODE_ENV=development
CORS_ORIGIN=http://localhost:3000
API_PREFIX=/api

Database Initialization โ€‹

bash
bun run db:push
bun run db:seed

Start Service โ€‹

bash
# Development mode
bun run dev

# Production mode
bun run build
bun run start

Visit http://localhost:3002

Project Structure โ€‹

halolight-api-bun/
โ”œโ”€โ”€ src/
โ”‚   โ”œโ”€โ”€ routes/          # Controllers/Route handlers
โ”‚   โ”œโ”€โ”€ services/        # Business logic layer
โ”‚   โ”œโ”€โ”€ db/              # Data models
โ”‚   โ”œโ”€โ”€ middleware/      # Middleware
โ”‚   โ”œโ”€โ”€ utils/           # Utility functions
โ”‚   โ””โ”€โ”€ index.ts         # Application entry
โ”œโ”€โ”€ test/                # Test files
โ”œโ”€โ”€ Dockerfile           # Docker configuration
โ”œโ”€โ”€ docker-compose.yml
โ””โ”€โ”€ package.json

API Modules โ€‹

Authentication Endpoints โ€‹

MethodPathDescriptionAuth
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 โ€‹

MethodPathDescriptionAuth
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) - 5 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) - 5 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) - 4 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) - 5 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) - 6 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/tasksPending tasks
GET/api/dashboard/calendarToday's events

Authentication Mechanism โ€‹

JWT Dual Token โ€‹

Access Token:  15 minutes validity, for API requests
Refresh Token: 7 days validity, for refreshing Access Token

Request Header โ€‹

http
Authorization: Bearer <access_token>

Refresh Flow โ€‹

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

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

Authorization 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 โ€‹

StatusError CodeDescription
400VALIDATION_ERRORValidation failed
401UNAUTHORIZEDUnauthorized
403FORBIDDENForbidden
404NOT_FOUNDResource not found
409CONFLICTResource conflict
500INTERNAL_ERRORServer error

Common Commands โ€‹

bash
# Development
bun run dev                 # Start development server
bun run build               # Production build
bun run start               # Run production build

# Build
bun run build               # Build production version

# Testing
bun test                    # Run unit tests
bun test --coverage         # Generate coverage report

# Database
bun run db:push             # Push schema to database
bun run db:generate         # Generate migration files
bun run db:migrate          # Run database migrations
bun run db:seed             # Seed test data
bun run db:studio           # Open Drizzle Studio

# Code Quality
bun run lint                # ESLint check
bun run lint:fix            # ESLint auto-fix
bun run type-check          # TypeScript type check

Deployment โ€‹

Docker โ€‹

bash
docker build -t halolight-api-bun .
docker run -p 3002:3002 halolight-api-bun

Docker Compose โ€‹

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

services:
  app:
    build: .
    ports:
      - "3002:3002"
    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 โ€‹

Running Tests โ€‹

bash
bun test                    # Run all tests
bun test --coverage         # Generate coverage report

Test Examples โ€‹

typescript
// Authentication test example
import { describe, test, expect } from 'bun:test';

describe('Auth API', () => {
  test('should login successfully', async () => {
    const response = await fetch('http://localhost:3002/api/auth/login', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        email: 'admin@example.com',
        password: 'admin123'
      })
    });

    const data = await response.json();
    expect(data.success).toBe(true);
    expect(data.data.accessToken).toBeDefined();
  });
});

Performance Metrics โ€‹

Benchmarks โ€‹

MetricValueCondition
Request Throughput~50,000 req/sSingle core, simple route
Average Response Time<5msLocal database
Memory Usage~30MBCold start
CPU Usage<10%Idle state

Observability โ€‹

Logging System โ€‹

typescript
// Logging configuration example
import { logger } from './utils/logger';

logger.info('User logged in', { userId: user.id });
logger.error('Database error', { error: err.message });

Health Check โ€‹

typescript
// GET /health
app.get('/health', (c) => {
  return c.json({
    status: 'healthy',
    timestamp: new Date().toISOString(),
    uptime: process.uptime()
  });
});

Monitoring Metrics โ€‹

typescript
// Prometheus metrics endpoint
app.get('/metrics', async (c) => {
  return c.text(await register.metrics());
});

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 use Bun's built-in password hashing? โ€‹

A: Use Bun.password API:

typescript
// Hash password
const hash = await Bun.password.hash(password, {
  algorithm: 'bcrypt',
  cost: 10
});

// Verify password
const isValid = await Bun.password.verify(password, hash, 'bcrypt');

Development Tools โ€‹

  • Drizzle Studio - Visual database management tool
  • Hoppscotch/Postman - API testing tools
  • ESLint + Prettier - Code formatting
  • Bun VSCode Extension - Bun syntax support

Comparison with Other Backends โ€‹

FeatureBun + HonoNestJSFastAPISpring Boot
LanguageTypeScriptTypeScriptPythonJava
ORMDrizzlePrismaSQLAlchemyJPA
Performanceโญโญโญโญโญโญโญโญโญโญโญโญโญโญโญโญ
Learning Curveโญโญโญโญโญโญโญโญโญโญโญโญโญ