Introduction

โปรเจคนี้เป็นส่วนหนึ่งในคอร์สเรียน Practical API Design ของ BorntoDev ผมจึงเอาหลักการที่ได้จากคอร์สเรียนมาประยุกต์ใช้กับโปรเจคนี้ โดย Stack ที่ใช้ในโปรเจคนี้ประกอบด้วย Node.js, Express, TypeScript

Project structure

เนื่องจากโจทย์ที่ได้มามีคำอธิบายที่ชัดเจน รวมถึงมีหลักการออกแบบ API ไว้ให้แล้ว ดังนั้นจึงสามารถแพลนโครงสร้างของโปรเจค ได้เลย

หมายเหตุ — โครงสร้างด้านล่างนี้คือ ของที่สร้างจริง ไม่ใช่ผังที่วางไว้ตอนเริ่ม จุดที่แผนเดิมต่างออกไปคือ core/db/pool.ts กับ migrations/ ซึ่งถูกตัดออกตอนตัดสินใจใช้ in-memory repository ตามกรอบ "small means small" ของโจทย์ (ดูหัวข้อ ข้อจำกัดที่รู้ตัว ท้ายหน้า) — repository จึงเป็น interface + adapter แทนที่จะเป็นที่อยู่ของ SQL

practical-api-design/
├── dist/                              # compiled JS (git ignored)
├── src/
│   ├── config/
│   │   └── env.ts                     # parse + validate process.env, fail fast
│   │
│   ├── modules/                       # one folder per domain
│   │   ├── auth/
│   │   │   ├── auth.routes.ts
│   │   │   ├── auth.controller.ts
│   │   │   ├── auth.service.ts        # register, login
│   │   │   ├── auth.service.test.ts
│   │   │   ├── token.ts               # sign + verify, HS256 pinned
│   │   │   └── token.test.ts          # ไม่มี auth.schema.ts — ใช้ users/user.schema.ts
│   │   ├── users/
│   │   │   ├── user.routes.ts
│   │   │   ├── user.controller.ts
│   │   │   ├── user.service.ts
│   │   │   ├── user.repository.ts     # PORT: interface only
│   │   │   ├── user.repository.memory.ts  # ADAPTER: the Map
│   │   │   ├── user.schema.ts         # + register/login schemas
│   │   │   ├── user.types.ts          # domain type, NOT the DB row
│   │   │   ├── email.ts               # normalizeEmail
│   │   │   ├── password.ts            # bcrypt hash + compare
│   │   │   ├── password.test.ts
│   │   │   ├── user.seed.ts           # seeds the admin at boot
│   │   │   └── user.service.test.ts   # UNIT test — colocated, inside rootDir
│   │   ├── products/                  # same shape (+ product.repository.memory.ts)
│   │   ├── orders/
│   │   │   ├── order.state.ts         # state machine: legal transitions
│   │   │   ├── order.state.test.ts
│   │   │   └── ...                    # same shape as users
│   │   └── payments/
│   │       ├── payment.gateway.ts     # PORT: interface only
│   │       ├── adapters/
│   │       │   └── fake.gateway.ts    # ADAPTER: the stub
│   │       └── ...                    # same shape as users
│   │
│   ├── middleware/                    # cross-cutting, Express-aware
│   │   ├── authenticate.ts            # verify JWT → req.user
│   │   ├── authorize.ts               # role check (factory: authorize('admin'))
│   │   ├── authorize.test.ts
│   │   ├── validate.ts                # schema → 422, factory over zod
│   │   ├── idempotency.ts
│   │   ├── idempotency.test.ts
│   │   ├── rate-limit.ts
│   │   ├── request-logger.ts          # morgan → winston
│   │   ├── error-handler.ts           # LAST. the only place errors → HTTP
│   │   └── error-handler.test.ts
│   │
│   ├── core/                          # framework-agnostic shared kernel
│   │   ├── container.ts               # the ONLY file that names an adapter
│   │   ├── errors/
│   │   │   ├── app-error.ts           # AppError + NotFound, Conflict, Forbidden...
│   │   │   └── http-mapper.ts         # domain error code → status code
│   │   ├── cache/
│   │   │   ├── cache.port.ts          # interface
│   │   │   ├── memory.cache.ts        # adapter (swap for redis later)
│   │   │   └── memory.cache.test.ts
│   │   ├── idempotency/
│   │   │   ├── idempotency.store.ts   # key persistence, not the middleware
│   │   │   ├── idempotency.store.memory.ts
│   │   │   └── idempotency.store.memory.test.ts
│   │   └── logger.ts                  # winston instance
│   │
│   ├── @types/
│   │   └── express/
│   │       └── index.d.ts             # declares req.id
│   │
│   ├── docs/
│   │   └── openapi.yaml               # design-first, เสิร์ฟที่ /docs
│   │
│   ├── routes/
│   │   ├── v1.ts                      # mounts every module under /api/v1
│   │   ├── health.ts                  # outside /api/v1 — infrastructure
│   │   └── docs.ts                    # swagger-ui + relaxed CSP, /docs only
│   │
│   ├── app.ts                         # express() + middleware chain + routes
│   └── server.ts                      # listen() + process-level handlers
│
├── tests/                             # OUTSIDE rootDir — integration only
│   ├── integration/                   # supertest, hits app.ts
│   │   ├── health.test.ts
│   │   ├── products.test.ts
│   │   ├── orders.test.ts
│   │   └── payments.test.ts
│   └── helpers/
│       └── auth.ts                    # createActor + resetContainer
│
├── .env
├── .env.example
├── .gitignore
├── jest.config.js                     # ESM + @swc/jest transform
├── jest.setup.js                      # test env vars
├── package.json
├── README.md
├── tsconfig.json                      # base — type-checks src/ AND tests/
└── tsconfig.build.json                # extends base: rootDir ./src, excludes
                                       # *.test.ts → tests never reach dist/

Error Handling first, and here's why?

ถึงแม้ Express จะมี default error handler ไว้ให้แล้ว แต่สิ่งที่ส่งมีเพียง stack trace ตอบกลับตอน dev และส่ง status 500 ตอน production — เราจึงต้องเขียน error handler ขึ้นมาเองเพื่อบอก client ถึงรายละเอียดของ error นั้น ๆ ตามหลัก User-friendly Errors และ Centralized Error Handling

แล้วทำไมถึงเริ่มจากการเขียน error handler ก่อน? เหตุผลก็คือ หากเขียน error handler ทีหลัง เราจะต้องไปตามแก้ route ทุก endpoint เพื่อให้ส่ง error ใน format เดียวกัน

จะเห็นว่า โครงสร้างที่ทำสำหรับ error handler ประกอบด้วย 3 ชั้น ตามหลัก Single Responsibility ซึ่งสามารถอธิบายหน้าที่แต่ละชั้นได้ดังนี้

app-error.ts — เก็บความหมายของ error เช่น NOT_FOUND

http-mapper.ts — แปลความหมาย → status code เป็นตัวแปลว่า NOT_FOUND คือ 404

error-handler.ts — เป็นชั้นที่ติดกับ Express คอยดักจับ error, เลือก log level และเขียน response

หมายเหตุ การออกแบบตามหลักการ SOLID เหมาะกับโปรเจคที่มีความซับซ้อนหรือขนาดใหญ่ เพราะข้อเสียของการออกแบบนี้ จะทำให้มีไฟล์, class เยอะกว่าการใช้ HttpError(statusCode, message)


Layering design

เหตุผลเบื้องหลัง design

เนื่องจาก Express ไม่ได้มีการบังคับให้จัดโครงสร้างโปรเจครูปแบบใดรูปแบบหนึ่ง แล้วทำไมเราไม่แค่เขียนทุกอย่างลงไปใน app.ts ไปเลยเหมือนตัวอย่าง code ด้านล่าง