6.1 KiB
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
- Cấu Trúc Dự Án
- Tiêu Chuẩn Code
- Quy Trình Git
- Phát Triển Backend
- Chiến Lược Testing
- Quy Trình Database
- 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épany(dùngunknownnế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
-
Đị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>; -
Tạo Service Method (
modules/user/user.service.ts):- Implement business logic.
- Sử dụng
BaseRepository. - Throw
HttpError(ví dụ:NotFound,BadRequest).
-
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 }).
- Parse body với DTO:
-
Đă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
- Sửa
prisma/schema.prisma. - Tạo migration (Dev):
./scripts/db/migrate.sh iam-service dev --name add_user_profile - Á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.