principletypescriptMajor
Resource Modeling: Design around business domains, not database tables
Viewed 0 times
dtodomaindatabasedecouplingschemaresourceaggregate
Problem
Exposing database table structures directly as API resources creates tight coupling between persistence and API layers, leaks implementation details, and makes schema migrations breaking changes.
Solution
Model API resources around business domain concepts. A single API resource may aggregate data from multiple tables. Use DTOs (Data Transfer Objects) or response schemas that are explicitly versioned and decoupled from ORM entities.
Why
The API surface is a contract with consumers. Database schemas change frequently for performance and normalization reasons; the API contract should be stable and semantically meaningful to business operations.
Gotchas
- Avoid exposing internal IDs from join tables as top-level resource identifiers.
- Do not leak database column names (e.g., user_created_at) directly — transform to camelCase created_at in JSON.
- Resource modeling decisions are hard to reverse once consumers depend on them.
Code Snippets
DTO separating API resource from DB entity
// DB entity (internal)
interface UserRow {
user_id: number
first_nm: string
last_nm: string
crt_ts: Date
}
// API resource (public contract)
interface UserResource {
id: string
firstName: string
lastName: string
createdAt: string // ISO 8601
}
function toUserResource(row: UserRow): UserResource {
return {
id: String(row.user_id),
firstName: row.first_nm,
lastName: row.last_nm,
createdAt: row.crt_ts.toISOString()
}
}Revisions (0)
No revisions yet.