Spaces:
Sleeping
Sleeping
Commit ·
42e30c2
1
Parent(s): 6ebdbe8
docs: extract technical content into bilingual docs
Browse files- Move architecture notes into docs/TECHNICAL.md
- Provide English and Vietnamese versions
- README.md +3 -127
- README.vi.md +382 -0
- docs/TECHNICAL.md +131 -0
- docs/TECHNICAL.vi.md +131 -0
README.md
CHANGED
|
@@ -1,5 +1,7 @@
|
|
| 1 |
# json-api-server
|
| 2 |
|
|
|
|
|
|
|
| 3 |
A JSONPlaceholder-compatible REST API built mostly with **Node.js built-ins** — the only runtime dependency is `argon2` for admin password hashing. Uses `node:sqlite` for storage and a custom Redis client implemented over the raw RESP protocol via TCP sockets.
|
| 4 |
|
| 5 |
## Technologies Used
|
|
@@ -321,117 +323,7 @@ curl -X DELETE http://localhost:3000/api/posts/1
|
|
| 321 |
curl http://localhost:3000/health
|
| 322 |
```
|
| 323 |
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
## Architecture
|
| 327 |
-
|
| 328 |
-
```
|
| 329 |
-
json-api-server/
|
| 330 |
-
├── bin/
|
| 331 |
-
│ └── start.js # Entry point — loads .env via src/config/load-env.js, starts server
|
| 332 |
-
├── src/
|
| 333 |
-
│ ├── config/
|
| 334 |
-
│ │ ├── index.js # Centralized config — auto-loads dotenv via load-env.js, exports camelCase
|
| 335 |
-
│ │ ├── load-env.js # Shared dotenv loader — auto-run on require, skips in production
|
| 336 |
-
│ │ ├── runtime-config.js # Thread-safe in-memory config overrides for runtime updates (rate-limit, Redis)
|
| 337 |
-
│ │ └── setting-defs.js # Setting definitions for 14 env vars (NODE_ENV, PORT, ADMIN_KEY, etc.)
|
| 338 |
-
│ ├── db/
|
| 339 |
-
│ │ ├── index.js # SQLite layer (node:sqlite) — CRUD operations (reads config)
|
| 340 |
-
│ │ ├── migrate.js # Table creation (standalone via npm run db:migrate)
|
| 341 |
-
│ │ ├── seed.js # Fetches seed data from JSONPlaceholder API, auto-runs migrate
|
| 342 |
-
│ │ ├── seed-settings.js # Seeds 14 env vars (NODE_ENV, PORT, ADMIN_KEY, etc.) into settings table
|
| 343 |
-
│ │ └── sql-logger.js # Shared Proxy wrappers — logs exec/prepare/run/get/all to stderr
|
| 344 |
-
│ ├── middleware/
|
| 345 |
-
│ │ └── rate-limiter.js # Rate limiter (Redis/in-memory, circuit breaker, escalating blocks)
|
| 346 |
-
│ ├── redis/
|
| 347 |
-
│ │ └── index.js # Pure-Node Redis client via RESP protocol over TCP
|
| 348 |
-
│ ├── public/
|
| 349 |
-
│ │ ├── favicon.ico # Favicon (ICO format)
|
| 350 |
-
│ │ ├── favicon.png # Favicon (PNG format)
|
| 351 |
-
│ │ └── license.md # Flaticon license file
|
| 352 |
-
│ └── server/
|
| 353 |
-
│ ├── index.js # HTTP server, graceful shutdown, startup orchestration
|
| 354 |
-
│ └── route.js # Route parser, request handlers, admin auth, favicon, runtime config updates
|
| 355 |
-
├── tests/
|
| 356 |
-
│ ├── config/
|
| 357 |
-
│ │ ├── config.test.js # Config defaults and env var branches (9)
|
| 358 |
-
│ │ └── load-env.test.js # Load-env file loading chain and error paths (7)
|
| 359 |
-
│ ├── db/
|
| 360 |
-
│ │ ├── database.test.js # Database CRUD, pagination, search, sort, SQL injection, cascade delete (11)
|
| 361 |
-
│ │ ├── migrate.test.js # Migration success and failure paths (2)
|
| 362 |
-
│ │ ├── seed.test.js # Seed with real DB + mocked deps, JSONPlaceholder fetch (5)
|
| 363 |
-
│ │ └── sql-logger.test.js # SQL query logger wrapping (5)
|
| 364 |
-
│ ├── middleware/
|
| 365 |
-
│ │ └── rate-limiter.test.js # In-memory, Redis, circuit breaker, proxy IPs, updateConfig (57)
|
| 366 |
-
│ ├── redis/
|
| 367 |
-
│ │ └── redis.test.js # RESP protocol encoding/parsing, constructor options, eval, reconnect (33)
|
| 368 |
-
│ ├── server/
|
| 369 |
-
│ │ ├── coverage-printlog.test.js # Printlog and server export V8 coverage (4)
|
| 370 |
-
│ │ ├── graceful-shutdown.test.js # SIGINT/SIGTERM handler coverage (1)
|
| 371 |
-
│ │ ├── index.test.js # Server request handler, admin auth, graceful shutdown (13)
|
| 372 |
-
│ │ ├── integration.test.js # API integration tests — real HTTP + SQLite, runtime PATCH (81)
|
| 373 |
-
│ │ └── route.test.js # Route parsing, favicon, health, admin auth cache, runtime config (18)
|
| 374 |
-
│ ├── README.md # Testing documentation (English)
|
| 375 |
-
│ ├── README.vi.md # Testing documentation (Vietnamese)
|
| 376 |
-
│ └── helpers/
|
| 377 |
-
│ ├── coverage.js # Test-coverage utilities (save/restore/setEnv/clearCjs/configMockFactory)
|
| 378 |
-
│ ├── index.js # startServer / stopServer / request utilities
|
| 379 |
-
│ ├── mock-factory.js # Mock factory helpers (mkDb/mkReq/mkRes/mkRedis/mkSettingsTable)
|
| 380 |
-
│ └── seed.js # Standalone script to create & seed temp DB
|
| 381 |
-
│ └── seed-settings-coverage.test.js # Seed-settings.js V8 coverage (4)
|
| 382 |
-
├── manual/
|
| 383 |
-
│ ├── admin.sh # Admin panel curl commands
|
| 384 |
-
│ ├── albums.sh # Albums endpoints
|
| 385 |
-
│ ├── comments.sh # Comments endpoints
|
| 386 |
-
│ ├── curl.sh # Quick curl commands
|
| 387 |
-
│ ├── health.sh # Health endpoint
|
| 388 |
-
│ ├── inspect-queries.sql # SQL queries for database inspection
|
| 389 |
-
│ ├── inspect.sh # Database inspection script
|
| 390 |
-
│ ├── inspect-docker-data.sh # Docker data inspection script
|
| 391 |
-
│ ├── photos.sh # Photos endpoints
|
| 392 |
-
│ ├── posts.sh # Posts endpoints
|
| 393 |
-
│ ├── todos.sh # Todos endpoints
|
| 394 |
-
│ └── users.sh # Users endpoints
|
| 395 |
-
├── manual-test-coverage/
|
| 396 |
-
│ ├── README.md # Coverage verification documentation
|
| 397 |
-
│ └── verify-commit-coverage.sh # Coverage verification script
|
| 398 |
-
├── Dockerfile # Docker image definition
|
| 399 |
-
├── docker-entrypoint.sh # Container entrypoint script
|
| 400 |
-
├── .dockerignore # Docker ignore rules
|
| 401 |
-
├── storage/ # SQLite database files (auto-created)
|
| 402 |
-
├── temp/ # Temporary files (gitignored)
|
| 403 |
-
├── .env # Base configuration (tried first in development — highest priority)
|
| 404 |
-
├── .env.dev # Development fallback (tried if .env not found)
|
| 405 |
-
├── .env.test # Test configuration (port 3001, separate DB, no rate limit)
|
| 406 |
-
├── .env.prod.example # Production template (copy to .env.prod)
|
| 407 |
-
├── .env.example # Reference for all available variables
|
| 408 |
-
├── package.json # Metadata and scripts
|
| 409 |
-
├── LICENSE # MIT license
|
| 410 |
-
├── README.md # Documentation
|
| 411 |
-
├── .gitignore # Git ignore rules
|
| 412 |
-
└── vitest.config.js # Vitest test runner configuration
|
| 413 |
-
```
|
| 414 |
-
|
| 415 |
-
### Startup Flow
|
| 416 |
-
|
| 417 |
-
```
|
| 418 |
-
bin/start.js → src/config/load-env.js (loads .env per NODE_ENV, skipped in production)
|
| 419 |
-
→ src/server/index.js
|
| 420 |
-
├── src/config/index.js (centralized config, auto-loads dotenv)
|
| 421 |
-
├── src/db/index.js (SQLite CRUD)
|
| 422 |
-
├── src/redis/index.js (pure RESP + AUTH + URL)
|
| 423 |
-
└── src/middleware/rate-limiter.js (Redis || in-memory, circuit breaker, escalating blocks)
|
| 424 |
-
|
| 425 |
-
# Standalone scripts: npm run db:migrate / npm run db:seed / npm run db:setup (config loads dotenv automatically)
|
| 426 |
-
```
|
| 427 |
-
|
| 428 |
-
### Request Flow
|
| 429 |
-
|
| 430 |
-
```
|
| 431 |
-
HTTP Request → CORS headers → Rate limiter → Route parser → Handler → JSON Response
|
| 432 |
-
```
|
| 433 |
-
|
| 434 |
-
---
|
| 435 |
|
| 436 |
## Database
|
| 437 |
|
|
@@ -479,22 +371,6 @@ npm run test:coverage # With coverage report (100% across all metrics)
|
|
| 479 |
```
|
| 480 |
|
| 481 |
See [tests/README.md](tests/README.md) for full documentation.
|
| 482 |
-
---
|
| 483 |
-
|
| 484 |
-
## Implementation Notes
|
| 485 |
-
|
| 486 |
-
- **Minimal runtime dependencies** — only `argon2` for admin password hashing; everything else uses Node.js built-in modules (`http`, `url`, `fs`, `path`, `net`, `node:sqlite`). `dotenv` is a dev dependency.
|
| 487 |
-
- **Pure RESP protocol** — the Redis client in `src/redis/index.js` implements the Redis serialization protocol over raw TCP sockets without any third-party library. Supports `AUTH` password authentication and `REDIS_URL` connection strings.
|
| 488 |
-
- **Centralized config** — all environment variables are read in `src/config/index.js` and exported as camelCase (`port`, `dbPath`, `redisOpts`, `rateLimitMax`, `dbDebugSql`, `sensitiveKeys`, etc.) for use across the codebase.
|
| 489 |
-
- **Rate limiter** — \`src/middleware/rate-limiter.js\` features a circuit breaker for Redis failures, CIDR-based trusted proxy IP extraction, escalating block durations (5m → 20m → 1h), atomic Redis Lua scripts, and an in-memory fallback with LRU eviction. \`createRateLimiter()\` accepts options directly instead of reading config lazily.
|
| 490 |
-
- **Runtime configuration** — Patching rate-limit or Redis settings via the admin API immediately applies changes through `RuntimeConfig` (in-memory overrides), avoiding server restarts. Rate-limit hot-swapping uses `rateLimiter.updateConfig()`; Redis reconnection uses `Redis.reconnect()`.
|
| 491 |
-
- **Testable seed script** — `src/db/seed.js` accepts `database` and `fetch` parameters via dependency injection, enabling full unit testing without mocking `require()`.
|
| 492 |
-
- **SQL query logging** — `src/db/sql-logger.js` exports `wrapDb`/`wrapStmt` Proxy wrappers that log `exec`, `prepare`, `run`, `get`, and `all` calls to stderr. `src/db/index.js` uses them via `getWrappedDb()` when `DEBUG_SQL=true`.
|
| 493 |
-
- **Multi-environment** — `src/config/index.js` requires `src/config/load-env.js` at module level, which chain-loads all dotenv files in priority order with `override: false` — existing `process.env` values and earlier files take precedence over later ones. Every consumer (server, migrate, seed) simply requires `src/config/index.js` and gets correct env values. In production, dotenv is skipped entirely — env vars must come from the deployment environment.
|
| 494 |
-
- **SQL injection prevention** — `src/db/index.js` validates `_sort` against a whitelist of known columns and quotes identifiers with `""`; LIKE wildcards (`%`, `_`) are escaped to prevent injection through the `q` parameter
|
| 495 |
-
- **Argon2 auth cache** — `src/server/route.js` caches `ADMIN_KEY` verification results in a `Map` with 5-second TTL and 1,000-entry limit, avoiding repeated argon2 hashing on burst admin requests
|
| 496 |
-
- **CORS** enabled on all routes
|
| 497 |
-
- **Graceful shutdown** — handles `SIGINT` and `SIGTERM` to close the server and Redis connection cleanly
|
| 498 |
|
| 499 |
## License
|
| 500 |
|
|
|
|
| 1 |
# json-api-server
|
| 2 |
|
| 3 |
+
> 🌐 Language / Ngôn ngữ: **English** | [Tiếng Việt](README.vi.md)
|
| 4 |
+
|
| 5 |
A JSONPlaceholder-compatible REST API built mostly with **Node.js built-ins** — the only runtime dependency is `argon2` for admin password hashing. Uses `node:sqlite` for storage and a custom Redis client implemented over the raw RESP protocol via TCP sockets.
|
| 6 |
|
| 7 |
## Technologies Used
|
|
|
|
| 323 |
curl http://localhost:3000/health
|
| 324 |
```
|
| 325 |
|
| 326 |
+
See [docs/TECHNICAL.md](docs/TECHNICAL.md) for detailed architecture and implementation notes.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 327 |
|
| 328 |
## Database
|
| 329 |
|
|
|
|
| 371 |
```
|
| 372 |
|
| 373 |
See [tests/README.md](tests/README.md) for full documentation.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 374 |
|
| 375 |
## License
|
| 376 |
|
README.vi.md
ADDED
|
@@ -0,0 +1,382 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# json-api-server
|
| 2 |
+
|
| 3 |
+
> 🌐 Language / Ngôn ngữ: [English](README.md) | **Tiếng Việt**
|
| 4 |
+
|
| 5 |
+
Một REST API tương thích JSONPlaceholder, được xây dựng chủ yếu bằng **Node.js built-ins** — dependency runtime duy nhất là `argon2` dùng để băm mật khẩu admin. Dùng `node:sqlite` để lưu trữ và một Redis client tự xây dựng trên giao thức RESP qua TCP sockets.
|
| 6 |
+
|
| 7 |
+
## Công nghệ sử dụng
|
| 8 |
+
|
| 9 |
+
- **Node.js >= 22** — runtime với `node:sqlite`, `node:http`, `node:net` tích hợp sẵn
|
| 10 |
+
- **node:sqlite** — cơ sở dữ liệu SQLite (tích hợp sẵn)
|
| 11 |
+
- **node:http** — HTTP server (tích hợp sẵn, không dùng Express/Fastify)
|
| 12 |
+
- **node:net** — TCP sockets cho Redis client RESP tự xây dựng (tích hợp sẵn)
|
| 13 |
+
- **argon2** — băm mật khẩu an toàn cho xác thực admin (dependency runtime duy nhất)
|
| 14 |
+
- **RESP protocol** — Redis client tự xây dựng, triển khai Redis Serialization Protocol qua TCP
|
| 15 |
+
- **dotenv** — tải file môi trường (chỉ là dev dependency, bỏ qua trong production)
|
| 16 |
+
- **vitest** — trình chạy kiểm thử với vùng phủ V8 gốc (dev dependency)
|
| 17 |
+
|
| 18 |
+
## Yêu cầu
|
| 19 |
+
|
| 20 |
+
- **Node.js >= 22** (dùng `node:sqlite` tích hợp sẵn)
|
| 21 |
+
- **Redis** (không bắt buộc — giới hạn tốc độ fallback về in-memory nếu không có)
|
| 22 |
+
|
| 23 |
+
## Bắt đầu nhanh
|
| 24 |
+
|
| 25 |
+
```bash
|
| 26 |
+
git clone <repo-url>
|
| 27 |
+
cd json-api-server
|
| 28 |
+
|
| 29 |
+
npm run db:setup # tạo bảng + dữ liệu mẫu (cần chạy trước lần đầu)
|
| 30 |
+
npm start # khởi động server
|
| 31 |
+
# hoặc với file watching cho phát triển:
|
| 32 |
+
npm run dev
|
| 33 |
+
```
|
| 34 |
+
|
| 35 |
+
## Docker
|
| 36 |
+
|
| 37 |
+
### Build
|
| 38 |
+
|
| 39 |
+
```bash
|
| 40 |
+
docker build -t json-api-server .
|
| 41 |
+
```
|
| 42 |
+
|
| 43 |
+
### Chạy
|
| 44 |
+
|
| 45 |
+
```bash
|
| 46 |
+
docker run -d -p 3000:3000 -v ./storage:/app/storage --name json-api-server json-api-server
|
| 47 |
+
```
|
| 48 |
+
|
| 49 |
+
Entrypoint tự động chạy `npm run db:setup` (migrate + seed) khi container khởi động.
|
| 50 |
+
|
| 51 |
+
### Biến môi trường
|
| 52 |
+
|
| 53 |
+
```bash
|
| 54 |
+
docker run -d -p 3000:3000 \
|
| 55 |
+
-e PORT=3000 \
|
| 56 |
+
-e ADMIN_KEY=my-secret-key \
|
| 57 |
+
-e REDIS_HOST=redis \
|
| 58 |
+
-v ./storage:/app/storage \
|
| 59 |
+
--name json-api-server json-api-server
|
| 60 |
+
```
|
| 61 |
+
|
| 62 |
+
### Ghi chú
|
| 63 |
+
|
| 64 |
+
- Container chạy với user `app` (không phải root).
|
| 65 |
+
- File database được lưu trong `/app/storage` (khai báo là `VOLUME`).
|
| 66 |
+
- `NODE_ENV=production` được đặt mặc định — dotenv **bị bỏ qua**, do đó mọi cấu hình phải được truyền qua biến môi trường (xem bên dưới).
|
| 67 |
+
- File `.env` và `.env.*` bị loại trừ bởi `.dockerignore` và **không được copy** vào image.
|
| 68 |
+
- Entrypoint chạy `npm run db:setup` khi container khởi động.
|
| 69 |
+
|
| 70 |
+
### Cấu hình môi trường
|
| 71 |
+
|
| 72 |
+
Container chạy với `NODE_ENV=production`, khi đó `src/config/load-env.js` **bỏ qua hoàn toàn dotenv**. Kết hợp với `.dockerignore` loại trừ mọi file `.env*`, bạn **bắt buộc** phải truyền cấu hình qua biến môi trường Docker.
|
| 73 |
+
|
| 74 |
+
**Khuyến nghị**: truyền biến trực tiếp:
|
| 75 |
+
|
| 76 |
+
```bash
|
| 77 |
+
docker run -d -p 3000:3000 \
|
| 78 |
+
-e PORT=3000 \
|
| 79 |
+
-e ADMIN_KEY=my-secret-key \
|
| 80 |
+
-e REDIS_HOST=redis \
|
| 81 |
+
-e SEED_API_BASE_URL=https://jsonplaceholder.typicode.com \
|
| 82 |
+
-v ./storage:/app/storage \
|
| 83 |
+
--name json-api-server json-api-server
|
| 84 |
+
```
|
| 85 |
+
|
| 86 |
+
**Cách khác — mount file env** (chỉ hoạt động với `NODE_ENV=production-local`):
|
| 87 |
+
|
| 88 |
+
```bash
|
| 89 |
+
docker run -d -p 3000:3000 \
|
| 90 |
+
-e NODE_ENV=production-local \
|
| 91 |
+
-v ./.env.prod:/app/.env.prod \
|
| 92 |
+
-v ./storage:/app/storage \
|
| 93 |
+
--name json-api-server json-api-server
|
| 94 |
+
```
|
| 95 |
+
|
| 96 |
+
> **Lưu ý:** Node 22 có thể hiển thị cảnh báo rằng `node:sqlite` đang ở giai đoạn thử nghiệm. Điều này vô hại.
|
| 97 |
+
|
| 98 |
+
---
|
| 99 |
+
|
| 100 |
+
## Cấu hình
|
| 101 |
+
|
| 102 |
+
File môi trường được tải bởi `src/config/load-env.js` (tự động chạy qua `src/config/index.js`). Tất cả file hiện có trong chuỗi đều được tải với `override: false` — giá trị `process.env` và file trước có quyền cao hơn file sau. Biến môi trường hệ thống luôn có quyền cao nhất (ví dụ: `PORT=5000 npm start`).
|
| 103 |
+
|
| 104 |
+
`NODE_ENV` mặc định là `development` nếu không được đặt. Trong môi trường **production**, `dotenv` **hoàn toàn bị bỏ qua** — hãy đặt biến môi trường thông qua môi trường triển khai của bạn (systemd, Docker, Kubernetes, v.v.).
|
| 105 |
+
|
| 106 |
+
| NODE_ENV | dotenv | Chuỗi fallback (thử theo thứ tự) |
|
| 107 |
+
|---------------------|--------|-----------------------------------|
|
| 108 |
+
| `development` | ✅ | `.env` ← `.env.dev` ← `.env.development` |
|
| 109 |
+
| `production-local` | ✅ | `.env.prod` ← `.env.production` |
|
| 110 |
+
| `test` | ✅ | `.env.test` |
|
| 111 |
+
| `production` | ❌ bỏ qua | _(dùng biến môi trường hệ thống)_ |
|
| 112 |
+
|
| 113 |
+
### Biến
|
| 114 |
+
|
| 115 |
+
| Biến | Mặc định | Mô tả |
|
| 116 |
+
|------------------------|-------------|----------------------------------------|
|
| 117 |
+
| `PORT` | `3000` | Cổng server |
|
| 118 |
+
| `DB_PATH` | `./storage/data.db` | Đường dẫn file SQLite |
|
| 119 |
+
| `REDIS_URL` | _(không)_ | URL kết nối Redis (ưu tiên cao hơn). Định dạng: `redis://user:password@host:port/db` |
|
| 120 |
+
| `REDIS_HOST` | `127.0.0.1` | Redis host |
|
| 121 |
+
| `REDIS_PORT` | `6379` | Redis port |
|
| 122 |
+
| `REDIS_DB` | `0` | Chỉ mục database Redis |
|
| 123 |
+
| `REDIS_PASSWORD` | _(không)_ | Mật khẩu Redis (cho `AUTH`) |
|
| 124 |
+
| `RATE_LIMIT_ENABLED` | `true` | Bật/tắt giới hạn tốc độ |
|
| 125 |
+
| `RATE_LIMIT_MAX` | `100` | Số request tối đa trong một khoảng thời gian |
|
| 126 |
+
| `DEBUG_SQL` | `false` | Ghi log tất cả truy vấn SQL ra stderr (`true`/`false`) |
|
| 127 |
+
| `RATE_LIMIT_WINDOW_MS` | `60000` | Khoảng thời gian tính bằng mili giây (mặc định 1 phút) |
|
| 128 |
+
| `SEED_API_BASE_URL` | `https://jsonplaceholder.typicode.com` | URL gốc cho API dữ liệu mẫu |
|
| 129 |
+
| `MAX_BODY_SIZE` | `1048576` | Kích thước body request tối đa tính bằng byte (tối thiểu 1) |
|
| 130 |
+
| `DEFAULT_PAGE_SIZE` | `10` | Số kết quả mặc định mỗi trang cho phân trang `_page`/`_limit` |
|
| 131 |
+
| `ADMIN_KEY` | _(không)_ | Khóa chính để xác thực request admin API (Bearer token) |
|
| 132 |
+
| **Cập nhật runtime** | — | Patching `RATE_LIMIT_ENABLED`, `RATE_LIMIT_MAX`, `RATE_LIMIT_WINDOW_MS`, `REDIS_URL`, `REDIS_HOST`, `REDIS_PORT`, `REDIS_DB`, hoặc `REDIS_PASSWORD` qua admin API áp dụng thay đổi ngay lập tức — không cần khởi động lại server |
|
| 133 |
+
|
| 134 |
+
---
|
| 135 |
+
|
| 136 |
+
## API Endpoints
|
| 137 |
+
|
| 138 |
+
### Tài nguyên
|
| 139 |
+
|
| 140 |
+
| Method | Path | Mô tả |
|
| 141 |
+
|----------|-----------------------------|------------------------------|
|
| 142 |
+
| `GET` | `/api/users` | Danh sách tất cả user |
|
| 143 |
+
| `GET` | `/api/users/:id` | Lấy user theo ID |
|
| 144 |
+
| `GET` | `/api/users/:id/posts` | Bài viết của user |
|
| 145 |
+
| `GET` | `/api/users/:id/albums` | Album của user |
|
| 146 |
+
| `GET` | `/api/users/:id/todos` | Việc cần làm của user |
|
| 147 |
+
| `GET` | `/api/posts` | Danh sách tất cả bài viết |
|
| 148 |
+
| `GET` | `/api/posts/:id` | Lấy bài viết theo ID |
|
| 149 |
+
| `GET` | `/api/posts/:id/comments` | Bình luận của bài viết |
|
| 150 |
+
| `GET` | `/api/comments` | Danh sách tất cả bình luận |
|
| 151 |
+
| `GET` | `/api/albums` | Danh sách tất cả album |
|
| 152 |
+
| `GET` | `/api/albums/:id/photos` | Ảnh trong album |
|
| 153 |
+
| `GET` | `/api/photos` | Danh sách tất cả ảnh |
|
| 154 |
+
| `GET` | `/api/todos` | Danh sách tất cả việc cần làm|
|
| 155 |
+
| `POST` | `/api/:table` | Tạo tài nguyên mới |
|
| 156 |
+
| `PUT` | `/api/:table/:id` | Thay thế toàn bộ tài nguyên |
|
| 157 |
+
| `PATCH` | `/api/:table/:id` | Cập nhật một phần |
|
| 158 |
+
| `DELETE` | `/api/:table/:id` | Xóa tài nguyên |
|
| 159 |
+
|
| 160 |
+
> **Xóa tầng (cascade)**: Xóa `user` sẽ xóa `posts`, `albums`, và `todos` của họ. Xóa `post` sẽ xóa `comments` của nó. Xóa `album` sẽ xóa `photos` của nó.
|
| 161 |
+
|
| 162 |
+
### Lọc theo query string và phân trang
|
| 163 |
+
|
| 164 |
+
```bash
|
| 165 |
+
# Lọc bài viết theo userId
|
| 166 |
+
GET /api/posts?userId=1
|
| 167 |
+
|
| 168 |
+
# Lọc việc cần làm theo userId và trạng thái hoàn thành
|
| 169 |
+
GET /api/todos?userId=1&completed=false
|
| 170 |
+
|
| 171 |
+
# Lọc bình luận theo postId
|
| 172 |
+
GET /api/comments?postId=1
|
| 173 |
+
```
|
| 174 |
+
|
| 175 |
+
Các cột có thể lọc khác nhau theo bảng (ví dụ: `title`, `email`, `username`). Trường `completed` chấp nhận chuỗi `true`/`false`.
|
| 176 |
+
|
| 177 |
+
### Phân trang
|
| 178 |
+
|
| 179 |
+
| Tham số | Mô tả | Ví dụ |
|
| 180 |
+
|-----------|------------------------------------------------|------------------------------|
|
| 181 |
+
| `_page` | Số trang (bắt đầu từ 1), dùng với `_limit` | `?_page=1&_limit=10` |
|
| 182 |
+
| `_limit` | Số mục mỗi trang (mặc định: `DEFAULT_PAGE_SIZE`)| `?_page=2&_limit=5` |
|
| 183 |
+
| `_start` | Chỉ số bắt đầu để cắt | `?_start=10&_end=20` |
|
| 184 |
+
| `_end` | Chỉ số kết thúc (không bao gồm) để cắt | `?_start=0&_end=5` |
|
| 185 |
+
|
| 186 |
+
### Tìm kiếm
|
| 187 |
+
|
| 188 |
+
Tìm kiếm trên các cột văn bản bằng tham số `q`. Các cột có thể tìm kiếm khác nhau theo bảng:
|
| 189 |
+
|
| 190 |
+
| Bảng | Cột có thể tìm kiếm |
|
| 191 |
+
|------------|-------------------------------------------|
|
| 192 |
+
| `users` | `name`, `username`, `email` |
|
| 193 |
+
| `posts` | `title`, `body` |
|
| 194 |
+
| `comments` | `name`, `email`, `body` |
|
| 195 |
+
| `albums` | `title` |
|
| 196 |
+
| `photos` | `title` |
|
| 197 |
+
| `todos` | `title` |
|
| 198 |
+
|
| 199 |
+
```bash
|
| 200 |
+
# Tìm bài viết theo tiêu đề hoặc nội dung
|
| 201 |
+
GET /api/posts?q=first
|
| 202 |
+
|
| 203 |
+
# Kết hợp tìm kiếm với bộ lọc
|
| 204 |
+
GET /api/posts?q=Post&userId=1
|
| 205 |
+
|
| 206 |
+
# Tìm việc cần làm
|
| 207 |
+
GET /api/todos?q=groceries
|
| 208 |
+
```
|
| 209 |
+
|
| 210 |
+
### Sắp xếp
|
| 211 |
+
|
| 212 |
+
| Tham số | Giá trị | Mô tả |
|
| 213 |
+
|----------|----------------|--------------------------------------|
|
| 214 |
+
| `_sort` | tên cột | Cột để sắp xếp |
|
| 215 |
+
| `_order` | `asc` / `desc` | Hướng sắp xếp (mặc định: `asc`) |
|
| 216 |
+
|
| 217 |
+
```bash
|
| 218 |
+
# Sắp xếp bài viết theo tiêu đề tăng dần
|
| 219 |
+
GET /api/posts?_sort=title&_order=asc
|
| 220 |
+
|
| 221 |
+
# Sắp xếp bài viết theo tiêu đề giảm dần
|
| 222 |
+
GET /api/posts?_sort=title&_order=desc
|
| 223 |
+
|
| 224 |
+
# Kết hợp sắp xếp với phân trang
|
| 225 |
+
GET /api/posts?_sort=id&_order=desc&_limit=2
|
| 226 |
+
```
|
| 227 |
+
|
| 228 |
+
### Endpoint hệ thống
|
| 229 |
+
|
| 230 |
+
| Path | Mô tả |
|
| 231 |
+
|-----------------------------------|--------------------------------------|
|
| 232 |
+
| `GET /` | Thông tin API với các endpoint có sẵn|
|
| 233 |
+
| `GET /api` | Thông tin API (giống như trên) |
|
| 234 |
+
| `GET /health` | Trạng thái server (Redis, bảng, cấu hình giới hạn tốc độ) |
|
| 235 |
+
| `GET /api/health` | Giống như trên |
|
| 236 |
+
| `GET /api/admin/settings` | Danh sách tất cả cài đặt (yêu cầu xác thực) |
|
| 237 |
+
| `PATCH /api/admin/settings/:key` | Cập nhật giá trị cài đặt — thay đổi rate-limit & Redis có **hiệu lực ngay lập tức** (yêu cầu xác thực) |
|
| 238 |
+
| `POST /api/admin/reset-database` | Xóa bảng dữ liệu và seed lại từ JSONPlaceholder (yêu cầu xác thực) |
|
| 239 |
+
|
| 240 |
+
### Admin API
|
| 241 |
+
|
| 242 |
+
Các endpoint admin được bảo vệ bằng xác thực Bearer token sử dụng biến môi trường `ADMIN_KEY`. Giá trị cài đặt được lưu trong bảng `settings` của database.
|
| 243 |
+
|
| 244 |
+
```bash
|
| 245 |
+
# Danh sách tất cả cài đặt
|
| 246 |
+
curl http://localhost:3000/api/admin/settings \
|
| 247 |
+
-H "Authorization: Bearer my-secret-key"
|
| 248 |
+
|
| 249 |
+
# Cập nhật cài đặt
|
| 250 |
+
curl -X PATCH http://localhost:3000/api/admin/settings/NODE_ENV \
|
| 251 |
+
-H "Authorization: Bearer my-secret-key" \
|
| 252 |
+
-H "Content-Type: application/json" \
|
| 253 |
+
-d '{"value": "production"}'
|
| 254 |
+
|
| 255 |
+
# Đặt lại database (xóa toàn bộ dữ liệu và tải lại từ JSONPlaceholder)
|
| 256 |
+
curl -X POST http://localhost:3000/api/admin/reset-database \
|
| 257 |
+
-H "Authorization: Bearer my-secret-key" \
|
| 258 |
+
-H "Content-Type: application/json" \
|
| 259 |
+
-d '{"confirm": true}'
|
| 260 |
+
```
|
| 261 |
+
|
| 262 |
+
`ADMIN_KEY` được băm bằng **argon2** trước khi lưu trữ. Khi cập nhật mật khẩu qua `PATCH /api/admin/settings/ADMIN_KEY`, giá trị mới tự động được băm. Mật khẩu không bao giờ được lưu dưới dạng văn bản thuần túy.
|
| 263 |
+
|
| 264 |
+
**Cập nhật cấu hình runtime**: Khi patching cài đặt rate-limit (`RATE_LIMIT_ENABLED`, `RATE_LIMIT_MAX`, `RATE_LIMIT_WINDOW_MS`) hoặc cài đặt kết nối Redis (`REDIS_HOST`, `REDIS_PORT`, `REDIS_DB`, `REDIS_PASSWORD`, `REDIS_URL`), server áp dụng thay đổi ngay lập tức qua lớp `RuntimeConfig` — không cần khởi động lại. Thay đổi rate-limit gọi `rateLimiter.updateConfig()` để hot-swap hành vi middleware, trong khi cài đặt Redis kích hoạt kết nối lại an toàn qua `Redis.reconnect()`.
|
| 265 |
+
|
| 266 |
+
Kết quả xác minh Argon2 được **lưu cache trong bộ nhớ 5 giây** cho mỗi token, tránh băm lặp lại trên các request admin liên tiếp. Khi có lỗi, kết quả cũng được lưu cache là không hợp lệ — ngăn chặn rò rỉ thông tin qua timing hoặc thông báo lỗi.
|
| 267 |
+
|
| 268 |
+
---
|
| 269 |
+
|
| 270 |
+
## Response Headers
|
| 271 |
+
|
| 272 |
+
Mọi response đều bao gồm header CORS và giới hạn tốc độ:
|
| 273 |
+
|
| 274 |
+
```
|
| 275 |
+
Access-Control-Allow-Origin: *
|
| 276 |
+
X-Powered-By: json-api-server/1.0
|
| 277 |
+
X-RateLimit-Limit: 100
|
| 278 |
+
X-RateLimit-Remaining: 99
|
| 279 |
+
X-RateLimit-Reset: 58 ← giây cho đến khi cửa sổ reset
|
| 280 |
+
X-RateLimit-Store: redis ← "redis" hoặc "memory"
|
| 281 |
+
```
|
| 282 |
+
|
| 283 |
+
Khi vượt quá giới hạn tốc độ, response `429 Too Many Requests` được trả về:
|
| 284 |
+
|
| 285 |
+
```
|
| 286 |
+
X-RateLimit-Limit: 100
|
| 287 |
+
X-RateLimit-Remaining: 0
|
| 288 |
+
X-RateLimit-Reset: 0
|
| 289 |
+
X-RateLimit-Store: redis
|
| 290 |
+
Retry-After: 300
|
| 291 |
+
```
|
| 292 |
+
|
| 293 |
+
```json
|
| 294 |
+
{
|
| 295 |
+
"error": "Too Many Requests",
|
| 296 |
+
"message": "Rate limit exceeded. Max 100 requests per 60s window.",
|
| 297 |
+
"retryAfter": 300
|
| 298 |
+
}
|
| 299 |
+
```
|
| 300 |
+
|
| 301 |
+
---
|
| 302 |
+
|
| 303 |
+
## Ví dụ
|
| 304 |
+
|
| 305 |
+
```bash
|
| 306 |
+
# Danh sách user
|
| 307 |
+
curl http://localhost:3000/api/users
|
| 308 |
+
|
| 309 |
+
# Tạo bài viết mới
|
| 310 |
+
curl -X POST http://localhost:3000/api/posts \
|
| 311 |
+
-H "Content-Type: application/json" \
|
| 312 |
+
-d '{"userId": 1, "title": "Hello", "body": "World"}'
|
| 313 |
+
|
| 314 |
+
# Cập nhật một phần
|
| 315 |
+
curl -X PATCH http://localhost:3000/api/posts/1 \
|
| 316 |
+
-H "Content-Type: application/json" \
|
| 317 |
+
-d '{"title": "Updated title"}'
|
| 318 |
+
|
| 319 |
+
# Xóa
|
| 320 |
+
curl -X DELETE http://localhost:3000/api/posts/1
|
| 321 |
+
|
| 322 |
+
# Kiểm tra sức khỏe
|
| 323 |
+
curl http://localhost:3000/health
|
| 324 |
+
```
|
| 325 |
+
|
| 326 |
+
Xem [docs/TECHNICAL.vi.md](docs/TECHNICAL.vi.md) để biết kiến trúc và ghi chú triển khai chi tiết.
|
| 327 |
+
|
| 328 |
+
## Database
|
| 329 |
+
|
| 330 |
+
- **7 bảng:** `users`, `posts`, `comments`, `albums`, `photos`, `todos`, `settings`
|
| 331 |
+
- **Chế độ WAL** cho hiệu suất đọc đồng thời tốt hơn
|
| 332 |
+
- **Ràng buộc khóa ngoại** được thực thi qua `PRAGMA foreign_keys=ON`
|
| 333 |
+
- **Dữ liệu mẫu** được lấy từ [JSONPlaceholder](https://jsonplaceholder.typicode.com) lần chạy đầu:
|
| 334 |
+
- 10 users (với `address` và `company` lưu dưới dạng JSON, phân tích khi đọc)
|
| 335 |
+
- 100 bài viết
|
| 336 |
+
- 500 bình luận
|
| 337 |
+
- 100 album
|
| 338 |
+
- 5000 ảnh
|
| 339 |
+
- 200 việc cần làm
|
| 340 |
+
- 14 cài đặt (biến môi trường: `NODE_ENV`, `PORT`, `DB_PATH`, `DEBUG_SQL`, `REDIS_HOST`, `REDIS_PORT`, `REDIS_DB`, `REDIS_PASSWORD`, `REDIS_URL`, `RATE_LIMIT_ENABLED`, `RATE_LIMIT_MAX`, `RATE_LIMIT_WINDOW_MS`, `DEFAULT_PAGE_SIZE`, `ADMIN_KEY`)
|
| 341 |
+
|
| 342 |
+
### Script hỗ trợ
|
| 343 |
+
|
| 344 |
+
```bash
|
| 345 |
+
sqlite3 storage/data.db < manual/inspect-queries.sql
|
| 346 |
+
```
|
| 347 |
+
|
| 348 |
+
Script này chạy các truy vấn toàn diện để kiểm tra số lượng dòng, metadata cột, quan hệ, kiểm tra toàn vẹn và thống kê.
|
| 349 |
+
|
| 350 |
+
### Script Database
|
| 351 |
+
|
| 352 |
+
| Script | Lệnh | Mô tả |
|
| 353 |
+
|---------------|---------------------------|-------------------------------------------------------|
|
| 354 |
+
| `db:migrate` | `npm run db:migrate` | Tạo 7 bảng (dotenv được tải bởi config.js) |
|
| 355 |
+
| `db:seed` | `npm run db:seed` | Lấy dữ liệu mẫu từ [JSONPlaceholder](https://jsonplaceholder.typicode.com), tự động chạy migrate + seed-settings |
|
| 356 |
+
| `db:seed-settings` | `npm run db:seed-settings` | Seed biến môi trường vào bảng `settings` (dotenv được tải bởi config.js) |
|
| 357 |
+
| `db:setup` | `npm run db:setup` | Chạy `db:seed` + `db:seed-settings` (migrate + JSONPlaceholder + env settings) |
|
| 358 |
+
| `test` | `npm test` | Chạy kiểm thử tích hợp vitest |
|
| 359 |
+
| `test:coverage` | `npm run test:coverage` | Chạy kiểm thử với báo cáo vùng phủ V8 |
|
| 360 |
+
|
| 361 |
+
---
|
| 362 |
+
|
| 363 |
+
## Kiểm thử
|
| 364 |
+
|
| 365 |
+
Sử dụng **vitest** với **vùng phủ V8 gốc**. **250 bài kiểm thử trên 14 file** bao phủ toàn bộ stack — từ kiểm thử tích hợp (HTTP server thật + SQLite) đến kiểm thử đơn vị cho mọi module.
|
| 366 |
+
|
| 367 |
+
```bash
|
| 368 |
+
npm test # Chạy tất cả kiểm thử một lần
|
| 369 |
+
npm run test:watch # Chế độ watch
|
| 370 |
+
npm run test:coverage # Với báo cáo vùng phủ (100% trên mọi chỉ số)
|
| 371 |
+
```
|
| 372 |
+
|
| 373 |
+
Xem [tests/README.md](tests/README.md) để biết tài liệu đầy đủ.
|
| 374 |
+
|
| 375 |
+
## Giấy phép
|
| 376 |
+
|
| 377 |
+
[MIT](LICENSE) — Bản quyền (c) 2026 Dang Khoa <i.am@dangkhoa.dev>
|
| 378 |
+
|
| 379 |
+
## Ghi công
|
| 380 |
+
|
| 381 |
+
Dự án này có sử dụng tài nguyên đồ họa từ Flaticon:
|
| 382 |
+
* [Sustainability stickers](https://www.flaticon.com/free-stickers/sustainability) được sáng tạo bởi [Manuel Viveros - Flaticon](https://www.flaticon.com/authors/manuel-viveros?type=sticker)
|
docs/TECHNICAL.md
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Technical Documentation
|
| 2 |
+
|
| 3 |
+
> 🌐 Language / Ngôn ngữ: **English** | [Tiếng Việt](TECHNICAL.vi.md)
|
| 4 |
+
|
| 5 |
+
> Architecture, implementation notes, and internal design of json-api-server.
|
| 6 |
+
|
| 7 |
+
## Architecture
|
| 8 |
+
|
| 9 |
+
```
|
| 10 |
+
json-api-server/
|
| 11 |
+
├── bin/
|
| 12 |
+
│ └── start.js # Entry point — loads .env via src/config/load-env.js, starts server
|
| 13 |
+
├── src/
|
| 14 |
+
│ ├── config/
|
| 15 |
+
│ │ ├── index.js # Centralized config — auto-loads dotenv via load-env.js, exports camelCase
|
| 16 |
+
│ │ ├── load-env.js # Shared dotenv loader — auto-run on require, skips in production
|
| 17 |
+
│ │ ├── runtime-config.js # Thread-safe in-memory config overrides for runtime updates (rate-limit, Redis)
|
| 18 |
+
│ │ └── setting-defs.js # Setting definitions for 14 env vars (NODE_ENV, PORT, ADMIN_KEY, etc.)
|
| 19 |
+
│ ├── db/
|
| 20 |
+
│ │ ├── index.js # SQLite layer (node:sqlite) — CRUD operations (reads config)
|
| 21 |
+
│ │ ├── migrate.js # Table creation (standalone via npm run db:migrate)
|
| 22 |
+
│ │ ├── seed.js # Fetches seed data from JSONPlaceholder API, auto-runs migrate
|
| 23 |
+
│ │ ├── seed-settings.js # Seeds 14 env vars (NODE_ENV, PORT, ADMIN_KEY, etc.) into settings table
|
| 24 |
+
│ │ └── sql-logger.js # Shared Proxy wrappers — logs exec/prepare/run/get/all to stderr
|
| 25 |
+
│ ├── middleware/
|
| 26 |
+
│ │ └── rate-limiter.js # Rate limiter (Redis/in-memory, circuit breaker, escalating blocks)
|
| 27 |
+
│ ├── redis/
|
| 28 |
+
│ │ └── index.js # Pure-Node Redis client via RESP protocol over TCP
|
| 29 |
+
│ ├── public/
|
| 30 |
+
│ │ ├── favicon.ico # Favicon (ICO format)
|
| 31 |
+
│ │ ├── favicon.png # Favicon (PNG format)
|
| 32 |
+
│ │ └── license.md # Flaticon license file
|
| 33 |
+
│ └── server/
|
| 34 |
+
│ ├── index.js # HTTP server, graceful shutdown, startup orchestration
|
| 35 |
+
│ └── route.js # Route parser, request handlers, admin auth, favicon, runtime config updates
|
| 36 |
+
├── tests/
|
| 37 |
+
│ ├── config/
|
| 38 |
+
│ │ ├── config.test.js # Config defaults and env var branches (9)
|
| 39 |
+
│ │ └── load-env.test.js # Load-env file loading chain and error paths (7)
|
| 40 |
+
│ ├── db/
|
| 41 |
+
│ │ ├── database.test.js # Database CRUD, pagination, search, sort, SQL injection, cascade delete (11)
|
| 42 |
+
│ │ ├── migrate.test.js # Migration success and failure paths (2)
|
| 43 |
+
│ │ ├── seed.test.js # Seed with real DB + mocked deps, JSONPlaceholder fetch (5)
|
| 44 |
+
│ │ └── sql-logger.test.js # SQL query logger wrapping (5)
|
| 45 |
+
│ ├── middleware/
|
| 46 |
+
│ │ └── rate-limiter.test.js # In-memory, Redis, circuit breaker, proxy IPs, updateConfig (57)
|
| 47 |
+
│ ├── redis/
|
| 48 |
+
│ │ └── redis.test.js # RESP protocol encoding/parsing, constructor options, eval, reconnect (33)
|
| 49 |
+
│ ├── server/
|
| 50 |
+
│ │ ├── coverage-printlog.test.js # Printlog and server export V8 coverage (4)
|
| 51 |
+
│ │ ├── graceful-shutdown.test.js # SIGINT/SIGTERM handler coverage (1)
|
| 52 |
+
│ │ ├── index.test.js # Server request handler, admin auth, graceful shutdown (13)
|
| 53 |
+
│ │ ├── integration.test.js # API integration tests — real HTTP + SQLite, runtime PATCH (81)
|
| 54 |
+
│ │ └── route.test.js # Route parsing, favicon, health, admin auth cache, runtime config (18)
|
| 55 |
+
│ ├── README.md # Testing documentation (English)
|
| 56 |
+
│ ├── README.vi.md # Testing documentation (Vietnamese)
|
| 57 |
+
│ └── helpers/
|
| 58 |
+
│ ├── coverage.js # Test-coverage utilities (save/restore/setEnv/clearCjs/configMockFactory)
|
| 59 |
+
│ ├── index.js # startServer / stopServer / request utilities
|
| 60 |
+
│ ├── mock-factory.js # Mock factory helpers (mkDb/mkReq/mkRes/mkRedis/mkSettingsTable)
|
| 61 |
+
│ └── seed.js # Standalone script to create & seed temp DB
|
| 62 |
+
│ └── seed-settings-coverage.test.js # Seed-settings.js V8 coverage (4)
|
| 63 |
+
├── manual/
|
| 64 |
+
│ ├── admin.sh # Admin panel curl commands
|
| 65 |
+
│ ├── albums.sh # Albums endpoints
|
| 66 |
+
│ ├── comments.sh # Comments endpoints
|
| 67 |
+
│ ├── curl.sh # Quick curl commands
|
| 68 |
+
│ ├── health.sh # Health endpoint
|
| 69 |
+
│ ├── inspect-queries.sql # SQL queries for database inspection
|
| 70 |
+
│ ├── inspect.sh # Database inspection script
|
| 71 |
+
│ ├── inspect-docker-data.sh # Docker data inspection script
|
| 72 |
+
│ ├── photos.sh # Photos endpoints
|
| 73 |
+
│ ├── posts.sh # Posts endpoints
|
| 74 |
+
│ ├── todos.sh # Todos endpoints
|
| 75 |
+
│ └── users.sh # Users endpoints
|
| 76 |
+
├── manual-test-coverage/
|
| 77 |
+
│ ├── README.md # Coverage verification documentation
|
| 78 |
+
│ └── verify-commit-coverage.sh # Coverage verification script
|
| 79 |
+
├── Dockerfile # Docker image definition
|
| 80 |
+
├── docker-entrypoint.sh # Container entrypoint script
|
| 81 |
+
├── .dockerignore # Docker ignore rules
|
| 82 |
+
├── storage/ # SQLite database files (auto-created)
|
| 83 |
+
├── temp/ # Temporary files (gitignored)
|
| 84 |
+
├── .env # Base configuration (tried first in development — highest priority)
|
| 85 |
+
├── .env.dev # Development fallback (tried if .env not found)
|
| 86 |
+
├── .env.test # Test configuration (port 3001, separate DB, no rate limit)
|
| 87 |
+
├── .env.prod.example # Production template (copy to .env.prod)
|
| 88 |
+
├── .env.example # Reference for all available variables
|
| 89 |
+
├── package.json # Metadata and scripts
|
| 90 |
+
├── LICENSE # MIT license
|
| 91 |
+
├── README.md # Documentation (English)
|
| 92 |
+
├── README.vi.md # Documentation (Vietnamese)
|
| 93 |
+
├── .gitignore # Git ignore rules
|
| 94 |
+
└── vitest.config.js # Vitest test runner configuration
|
| 95 |
+
```
|
| 96 |
+
|
| 97 |
+
### Startup Flow
|
| 98 |
+
|
| 99 |
+
```
|
| 100 |
+
bin/start.js → src/config/load-env.js (loads .env per NODE_ENV, skipped in production)
|
| 101 |
+
→ src/server/index.js
|
| 102 |
+
├── src/config/index.js (centralized config, auto-loads dotenv)
|
| 103 |
+
├── src/db/index.js (SQLite CRUD)
|
| 104 |
+
├── src/redis/index.js (pure RESP + AUTH + URL)
|
| 105 |
+
└── src/middleware/rate-limiter.js (Redis || in-memory, circuit breaker, escalating blocks)
|
| 106 |
+
|
| 107 |
+
# Standalone scripts: npm run db:migrate / npm run db:seed / npm run db:setup (config loads dotenv automatically)
|
| 108 |
+
```
|
| 109 |
+
|
| 110 |
+
### Request Flow
|
| 111 |
+
|
| 112 |
+
```
|
| 113 |
+
HTTP Request → CORS headers → Rate limiter → Route parser → Handler → JSON Response
|
| 114 |
+
```
|
| 115 |
+
|
| 116 |
+
---
|
| 117 |
+
|
| 118 |
+
## Implementation Notes
|
| 119 |
+
|
| 120 |
+
- **Minimal runtime dependencies** — only `argon2` for admin password hashing; everything else uses Node.js built-in modules (`http`, `url`, `fs`, `path`, `net`, `node:sqlite`). `dotenv` is a dev dependency.
|
| 121 |
+
- **Pure RESP protocol** — the Redis client in `src/redis/index.js` implements the Redis serialization protocol over raw TCP sockets without any third-party library. Supports `AUTH` password authentication and `REDIS_URL` connection strings.
|
| 122 |
+
- **Centralized config** — all environment variables are read in `src/config/index.js` and exported as camelCase (`port`, `dbPath`, `redisOpts`, `rateLimitMax`, `dbDebugSql`, `sensitiveKeys`, etc.) for use across the codebase.
|
| 123 |
+
- **Rate limiter** — `src/middleware/rate-limiter.js` features a circuit breaker for Redis failures, CIDR-based trusted proxy IP extraction, escalating block durations (5m → 20m → 1h), atomic Redis Lua scripts, and an in-memory fallback with LRU eviction. `createRateLimiter()` accepts options directly instead of reading config lazily.
|
| 124 |
+
- **Runtime configuration** — Patching rate-limit or Redis settings via the admin API immediately applies changes through `RuntimeConfig` (in-memory overrides), avoiding server restarts. Rate-limit hot-swapping uses `rateLimiter.updateConfig()`; Redis reconnection uses `Redis.reconnect()`.
|
| 125 |
+
- **Testable seed script** — `src/db/seed.js` accepts `database` and `fetch` parameters via dependency injection, enabling full unit testing without mocking `require()`.
|
| 126 |
+
- **SQL query logging** — `src/db/sql-logger.js` exports `wrapDb`/`wrapStmt` Proxy wrappers that log `exec`, `prepare`, `run`, `get`, and `all` calls to stderr. `src/db/index.js` uses them via `getWrappedDb()` when `DEBUG_SQL=true`.
|
| 127 |
+
- **Multi-environment** — `src/config/index.js` requires `src/config/load-env.js` at module level, which chain-loads all dotenv files in priority order with `override: false` — existing `process.env` values and earlier files take precedence over later ones. Every consumer (server, migrate, seed) simply requires `src/config/index.js` and gets correct env values. In production, dotenv is skipped entirely — env vars must come from the deployment environment.
|
| 128 |
+
- **SQL injection prevention** — `src/db/index.js` validates `_sort` against a whitelist of known columns and quotes identifiers with `""`; LIKE wildcards (`%`, `_`) are escaped to prevent injection through the `q` parameter
|
| 129 |
+
- **Argon2 auth cache** — `src/server/route.js` caches `ADMIN_KEY` verification results in a `Map` with 5-second TTL and 1,000-entry limit, avoiding repeated argon2 hashing on burst admin requests
|
| 130 |
+
- **CORS** enabled on all routes
|
| 131 |
+
- **Graceful shutdown** — handles `SIGINT` and `SIGTERM` to close the server and Redis connection cleanly
|
docs/TECHNICAL.vi.md
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Tài liệu kỹ thuật
|
| 2 |
+
|
| 3 |
+
> 🌐 Language / Ngôn ngữ: [English](TECHNICAL.md) | **Tiếng Việt**
|
| 4 |
+
|
| 5 |
+
> Kiến trúc, ghi chú triển khai và thiết kế nội bộ của json-api-server.
|
| 6 |
+
|
| 7 |
+
## Kiến trúc
|
| 8 |
+
|
| 9 |
+
```
|
| 10 |
+
json-api-server/
|
| 11 |
+
├── bin/
|
| 12 |
+
│ └── start.js # Điểm vào — tải .env qua src/config/load-env.js, khởi động server
|
| 13 |
+
├── src/
|
| 14 |
+
│ ├── config/
|
| 15 |
+
│ │ ├── index.js # Cấu hình tập trung — tự động tải dotenv qua load-env.js, xuất camelCase
|
| 16 |
+
│ │ ├── load-env.js # Trình tải dotenv dùng chung — tự động chạy khi require, bỏ qua trong production
|
| 17 |
+
│ │ ├── runtime-config.js # Ghi đè cấu hình trong bộ nhớ an toàn luồng cho cập nhật runtime (rate-limit, Redis)
|
| 18 |
+
│ │ └── setting-defs.js # Định nghĩa cài đặt cho 14 biến môi trường (NODE_ENV, PORT, ADMIN_KEY, v.v.)
|
| 19 |
+
│ ├── db/
|
| 20 |
+
│ │ ├── index.js # Lớp SQLite (node:sqlite) — thao tác CRUD (đọc config)
|
| 21 |
+
│ │ ├── migrate.js # Tạo bảng (chạy độc lập qua npm run db:migrate)
|
| 22 |
+
│ │ ├── seed.js # Lấy dữ liệu mẫu từ JSONPlaceholder API, tự động chạy migrate
|
| 23 |
+
│ │ ├── seed-settings.js # Seed 14 biến môi trường (NODE_ENV, PORT, ADMIN_KEY, v.v.) vào bảng settings
|
| 24 |
+
│ │ └── sql-logger.js # Proxy wrapper dùng chung — ghi log exec/prepare/run/get/all ra stderr
|
| 25 |
+
│ ├── middleware/
|
| 26 |
+
│ │ └── rate-limiter.js # Giới hạn tốc độ (Redis/in-memory, circuit breaker, escalating blocks)
|
| 27 |
+
│ ├── public/
|
| 28 |
+
│ │ ├── favicon.ico # Favicon (định dạng ICO)
|
| 29 |
+
│ │ ├── favicon.png # Favicon (định dạng PNG)
|
| 30 |
+
│ │ └── license.md # File giấy phép Flaticon
|
| 31 |
+
│ ├── redis/
|
| 32 |
+
│ │ └── index.js # Redis client thuần Node qua giao thức RESP trên TCP
|
| 33 |
+
│ └── server/
|
| 34 |
+
│ ├── index.js # HTTP server, graceful shutdown, điều phối khởi động
|
| 35 |
+
│ └── route.js # Phân tích route, handler request, xác thực admin, favicon, cập nhật cấu hình runtime
|
| 36 |
+
├── tests/
|
| 37 |
+
│ ├── config/
|
| 38 |
+
│ │ ├── config.test.js # Config mặc định và nhánh biến môi trường (9)
|
| 39 |
+
│ │ └── load-env.test.js # Tải chuỗi dotenv, override:false, bỏ qua production, fallback (7)
|
| 40 |
+
│ ├── db/
|
| 41 |
+
│ │ ├── database.test.js # CRUD database, phân trang, tìm kiếm, sắp xếp, SQL injection, cascade delete (11)
|
| 42 |
+
│ │ ├── migrate.test.js # Đường dẫn migration thành công và thất bại (2)
|
| 43 |
+
│ │ ├── seed.test.js # Seed với DB thật + mock dependencies, JSONPlaceholder fetch (5)
|
| 44 |
+
│ │ └── sql-logger.test.js # Bọc SQL query logger (5)
|
| 45 |
+
│ ├── middleware/
|
| 46 |
+
│ │ └── rate-limiter.test.js # In-memory, Redis, circuit breaker, proxy IPs, updateConfig (57)
|
| 47 |
+
│ ├── redis/
|
| 48 |
+
│ │ └── redis.test.js # Mã hóa/giải mã giao thức RESP, tùy chọn constructor, eval, reconnect (33)
|
| 49 |
+
│ ├── server/
|
| 50 |
+
│ │ ├── coverage-printlog.test.js # Printlog và V8 coverage xuất server (4)
|
| 51 |
+
│ │ ├── graceful-shutdown.test.js # Vùng phủ handler SIGINT/SIGTERM (1)
|
| 52 |
+
│ │ ├── index.test.js # Handler request server, admin auth, tắt máy an toàn (13)
|
| 53 |
+
│ │ ├── integration.test.js # Kiểm thử tích hợp API — HTTP thật + SQLite, runtime PATCH (81)
|
| 54 |
+
│ │ └── route.test.js # Phân tích route, favicon, health, cache xác thực admin, runtime config (18)
|
| 55 |
+
│ ├── README.md # Tài liệu kiểm thử (tiếng Anh)
|
| 56 |
+
│ ├── README.vi.md # Tài liệu kiểm thử (tiếng Việt)
|
| 57 |
+
│ └── helpers/
|
| 58 |
+
│ ├── coverage.js # Tiện ích vùng phủ kiểm thử (save/restore/setEnv/clearCjs/configMockFactory)
|
| 59 |
+
│ ├── index.js # Tiện ích startServer / stopServer / request
|
| 60 |
+
│ ├── mock-factory.js # Hàm factory mock (mkDb/mkReq/mkRes/mkRedis/mkSettingsTable)
|
| 61 |
+
│ └── seed.js # Script độc lập để tạo và seed DB tạm thời
|
| 62 |
+
│ └── seed-settings-coverage.test.js # Vùng phủ V8 seed-settings.js — DB thật + mock DB paths (4)
|
| 63 |
+
├── manual/
|
| 64 |
+
│ ├── admin.sh # Lệnh curl admin panel
|
| 65 |
+
│ ├── albums.sh # Endpoint albums
|
| 66 |
+
│ ├── comments.sh # Endpoint comments
|
| 67 |
+
│ ├── curl.sh # Lệnh curl nhanh
|
| 68 |
+
│ ├── health.sh # Endpoint health
|
| 69 |
+
│ ├── inspect-queries.sql # Truy vấn SQL để kiểm tra database
|
| 70 |
+
│ ├── inspect.sh # Script kiểm tra database
|
| 71 |
+
│ ├── inspect-docker-data.sh # Script kiểm tra dữ liệu Docker
|
| 72 |
+
│ ├── photos.sh # Endpoint photos
|
| 73 |
+
│ ├── posts.sh # Endpoint posts
|
| 74 |
+
│ ├── todos.sh # Endpoint todos
|
| 75 |
+
│ └── users.sh # Endpoint users
|
| 76 |
+
├── manual-test-coverage/
|
| 77 |
+
│ ├── README.md # Tài liệu kiểm tra vùng phủ
|
| 78 |
+
│ └── verify-commit-coverage.sh # Script kiểm tra vùng phủ
|
| 79 |
+
├── Dockerfile # Định nghĩa image Docker
|
| 80 |
+
├── docker-entrypoint.sh # Script entrypoint container
|
| 81 |
+
├── .dockerignore # Quy tắc ignore Docker
|
| 82 |
+
├── storage/ # File SQLite database (tự động tạo)
|
| 83 |
+
├── temp/ # File tạm thời (đã gitignore)
|
| 84 |
+
├── .env # Cấu hình cơ bản (được thử đầu tiên trong development — ưu tiên cao nhất)
|
| 85 |
+
├── .env.dev # Fallback development (được thử nếu không tìm thấy .env)
|
| 86 |
+
├── .env.test # Cấu hình test (cổng 3001, DB riêng, không giới hạn tốc độ)
|
| 87 |
+
├── .env.prod.example # Mẫu production (copy thành .env.prod)
|
| 88 |
+
├── .env.example # Tham chiếu cho tất cả biến có sẵn
|
| 89 |
+
├── package.json # Metadata và scripts
|
| 90 |
+
├── LICENSE # Giấy phép MIT
|
| 91 |
+
├── README.md # Tài liệu (tiếng Anh)
|
| 92 |
+
├── README.vi.md # Tài liệu (tiếng Việt)
|
| 93 |
+
├── .gitignore # Quy tắc ignore Git
|
| 94 |
+
└── vitest.config.js # Cấu hình trình chạy kiểm thử Vitest
|
| 95 |
+
```
|
| 96 |
+
|
| 97 |
+
### Luồng khởi động
|
| 98 |
+
|
| 99 |
+
```
|
| 100 |
+
bin/start.js → src/config/load-env.js (tải .env theo NODE_ENV, bỏ qua trong production)
|
| 101 |
+
→ src/server/index.js
|
| 102 |
+
├── src/config/index.js (cấu hình tập trung, tự động tải dotenv)
|
| 103 |
+
├── src/db/index.js (SQLite CRUD)
|
| 104 |
+
├── src/redis/index.js (RESP thuần + AUTH + URL)
|
| 105 |
+
└── src/middleware/rate-limiter.js (Redis || in-memory, circuit breaker, escalating blocks)
|
| 106 |
+
|
| 107 |
+
# Script độc lập: npm run db:migrate / npm run db:seed / npm run db:setup (config tải dotenv tự động)
|
| 108 |
+
```
|
| 109 |
+
|
| 110 |
+
### Luồng request
|
| 111 |
+
|
| 112 |
+
```
|
| 113 |
+
HTTP Request → CORS headers → Rate limiter → Phân tích route → Handler → JSON Response
|
| 114 |
+
```
|
| 115 |
+
|
| 116 |
+
---
|
| 117 |
+
|
| 118 |
+
## Ghi chú triển khai
|
| 119 |
+
|
| 120 |
+
- **Runtime dependencies tối thiểu** — chỉ có `argon2` để băm mật khẩu admin; mọi thứ khác đều dùng module built-in của Node.js (`http`, `url`, `fs`, `path`, `net`, `node:sqlite`). `dotenv` là dev dependency.
|
| 121 |
+
- **Giao thức RESP thuần** — Redis client trong `src/redis/index.js` triển khai giao thức tuần tự hóa Redis qua TCP sockets mà không cần thư viện bên thứ ba. Hỗ trợ xác thực mật khẩu `AUTH` và chuỗi kết nối `REDIS_URL`.
|
| 122 |
+
- **Cấu hình tập trung** — tất cả biến môi trường được đọc trong `src/config/index.js` và xuất dưới dạng camelCase (`port`, `dbPath`, `redisOpts`, `rateLimitMax`, `dbDebugSql`, v.v.) để sử dụng trên toàn bộ codebase.
|
| 123 |
+
- **Rate limiter** — `src/middleware/rate-limiter.js` có circuit breaker cho Redis lỗi, trích xuất IP proxy đáng tin cậy dựa trên CIDR, thời gian chặn tăng dần (5 ph → 20 ph → 1 giờ), Lua script Redis nguyên tử, và fallback in-memory với LRU eviction. `createRateLimiter()` nhận tùy chọn trực tiếp thay vì đọc config lazily.
|
| 124 |
+
- **Cấu hình runtime** — Patching cài đặt rate-limit hoặc Redis qua admin API áp dụng thay đổi ngay lập tức thông qua `RuntimeConfig` (ghi đè trong bộ nhớ), tránh khởi động lại server. Hot-swap rate-limit dùng `rateLimiter.updateConfig()`; kết nối lại Redis dùng `Redis.reconnect()`.
|
| 125 |
+
- **Script seed có thể kiểm thử** — `src/db/seed.js` chấp nhận tham số `database` và `fetch` qua dependency injection, cho phép kiểm thử đơn vị đầy đủ mà không cần mock `require()`.
|
| 126 |
+
- **Ghi log SQL** — `src/db/sql-logger.js` xuất các wrapper Proxy `wrapDb`/`wrapStmt` ghi log các lệnh gọi `exec`, `prepare`, `run`, `get`, và `all` ra stderr. `src/db/index.js` sử dụng chúng qua `getWrappedDb()` khi `DEBUG_SQL=true`.
|
| 127 |
+
- **Đa môi trường** — `src/config/index.js` require `src/config/load-env.js` ở cấp module, module này tải theo chuỗi tất cả file dotenv với `override: false` — giá trị `process.env` hiện có và file trước có quyền cao hơn file sau. Mọi consumer (server, migrate, seed) chỉ cần require `src/config/index.js` và nhận giá trị env chính xác. Trong production, dotenv bị bỏ qua hoàn toàn — biến env phải đến từ môi trường triển khai.
|
| 128 |
+
- **Ngăn chặn SQL injection** — `src/db/index.js` xác thực `_sort` với danh sách trắng các cột đã biết và đặt tên cột trong `""`; ký tự đại diện LIKE (`%`, `_`) được thoát để ngăn chặn injection qua tham số `q`
|
| 129 |
+
- **Cache xác thực Argon2** — `src/server/route.js` lưu cache kết quả xác minh `ADMIN_KEY` trong `Map` với TTL 5 giây và giới hạn 1.000 mục, tránh băm argon2 lặp lại trên các request admin burst
|
| 130 |
+
- **CORS** được bật trên tất cả các route
|
| 131 |
+
- **Tắt máy an toàn** — xử lý `SIGINT` và `SIGTERM` để đóng server và kết nối Redis sạch sẽ
|