Files
pos-system/docs/vi/guides/development.md

6.1 KiB

Hướng Dẫn Development

Lưu ý: Hướng dẫn này cung cấp các tiêu chuẩn và quy trình toàn diện để đóng góp vào GoodGo Microservices Platform.

Mục lục

  1. Cấu Trúc Dự Án
  2. Tiêu Chuẩn Code
  3. Quy Trình Git
  4. Phát Triển Backend
  5. Chiến Lược Testing
  6. Quy Trình Database
  7. Triển Khai Kubernetes

Cấu Trúc Dự Án

Chúng tôi tuân theo cấu trúc monorepo quản lý bởi PNPM Workspaces.

Base/
├── apps/                 # Ứng dụng Frontend
│   ├── web-client/       # Next.js 14+ (App Router)
│   └── mobile-client/    # Flutter
├── services/             # Backend microservices
│   ├── _template/        # Template cho service mới
│   ├── iam-service/      # Identity & Access Management
│   └── ...
├── packages/             # Thư viện chia sẻ
│   ├── logger/           # Structured logging (Winston)
│   ├── types/            # DTOs & Interfaces chia sẻ
│   ├── http-client/      # Internal Service Client
│   └── tracing/          # Cấu hình OpenTelemetry
├── infra/                # Infrastructure-as-Code
│   ├── traefik/          # API Gateway
│   └── databases/        # Scripts thiết lập Database
└── docs/                 # Tài liệu (EN & VI)

Tiêu Chuẩn Code

Quy ước Đặt tên

  • Files: kebab-case.ts (ví dụ: user.controller.ts, app.config.ts)
  • Classes: PascalCase (ví dụ: UserController, AuthService)
  • Functions/Variables: camelCase (ví dụ: getUserById, isValid)
  • Constants: UPPER_SNAKE_CASE (ví dụ: MAX_RETRIES, DEFAULT_TIMEOUT)
  • Interfaces: PascalCase (ví dụ: User, CreateUserDto) - Không dùng tiền tố 'I'

Bilingual Comments (Bình luận Song ngữ)

Đối với logic cốt lõi và public APIs, giả định cả lập trình viên quốc tế và Việt Nam đều đọc code.

/**
 * EN: Validates user credentials and returns a token
 * VI: Xác thực thông tin người dùng và trả về token
 */
async login(dto: LoginDto): Promise<TokenResponse> { ... }

TypeScript Usage

  • Strict Mode: Được bật trong tsconfig.json. Không cho phép any (dùng unknown nếu cần).
  • DTOs: Sử dụng Zod để runtime validation và type inference.
  • Return Types: Khai báo rõ ràng kiểu trả về cho tất cả public methods.

Quy Trình Git

Chiến lược Nhánh (Branching Strategy)

  • main: Code production-ready.
  • develop: Nhánh integration cho release tiếp theo.
  • feature/xyz: Tính năng mới (tách từ develop).
  • fix/xyz: Sửa lỗi (tách từ develop).
  • hotfix/xyz: Sửa lỗi nghiêm trọng (tách từ main).

Commit Messages

Chúng tôi tuân theo Conventional Commits:

feat(iam): add multi-factor authentication
fix(db): correct unique constraint on email
docs(guide): update development setup
style: format code with prettier
refactor: simplify auth middleware
test: add unit tests for user service
chore: update dependencies

Phát Triển Backend

Tạo API Endpoint Mới

  1. Định nghĩa DTO (modules/user/user.dto.ts):

    export const CreateUserDto = z.object({
      email: z.string().email(),
      name: z.string().min(2),
    });
    export type CreateUserDto = z.infer<typeof CreateUserDto>;
    
  2. Tạo Service Method (modules/user/user.service.ts):

    • Implement business logic.
    • Sử dụng BaseRepository.
    • Throw HttpError (ví dụ: NotFound, BadRequest).
  3. Tạo Controller (modules/user/user.controller.ts):

    • Parse body với DTO: const dto = CreateUserDto.parse(req.body).
    • Gọi service.
    • Trả về success response: res.json({ success: true, data: result }).
  4. Đăng ký Route (modules/user/index.ts):

    • Thêm vào Express router cùng middlewares.

Xử lý Lỗi (Error Handling)

Luôn sử dụng các class lỗi tùy chỉnh từ core/errors:

import { NotFoundError, ConflictError } from '../../core/errors';

if (!user) {
  throw new NotFoundError('User not found');
}

Chiến Lược Testing

Unit Tests (*.test.ts)

  • Phạm vi: Các class/function đơn lẻ.
  • Mocking: Mock tất cả dependencies bên ngoài (DB, services khác) dùng jest-mock-extended.
  • Vị trí: Đặt cùng thư mục với file source.
  • Chạy: pnpm test

E2E Tests (tests/**/*.e2e.ts)

  • Phạm vi: Full API flows (Controller -> Service -> DB).
  • Database: Sử dụng test database riêng biệt (Dockerized).
  • Chạy: pnpm test:e2e

Linting & Formatting

  • Lint: pnpm lint (ESLint)
  • Format: pnpm format (Prettier)
  • Typecheck: pnpm typecheck (TSC)

Quy Trình Database

Chúng tôi sử dụng Prisma với Neon PostgreSQL.

Migrations

  1. Sửa prisma/schema.prisma.
  2. Tạo migration (Dev):
    ./scripts/db/migrate.sh iam-service dev --name add_user_profile
    
  3. Áp dụng cho Production (CI/CD):
    ./scripts/db/migrate.sh iam-service deploy
    

Seed Data

Nạp dữ liệu mẫu vào database:

./scripts/db/seed.sh iam-service

Xem Dữ liệu Trực quan

Sử dụng Prisma Studio:

pnpm --filter @goodgo/iam-service prisma studio

Triển Khai Kubernetes

Để test Kubernetes cục bộ (Docker Desktop / Minikube):

# 1. Build images
docker build -t goodgo/iam-service:latest -f services/iam-service/Dockerfile .

# 2. Deploy
cd deployments/local/kubernetes
./deploy.sh

# 3. Xác minh
kubectl get pods -n iam-local
kubectl logs -f -l app=iam-service -n iam-local

Xem Hướng Dẫn Kubernetes để biết chi tiết.