Next.js từ cơ bản đến nâng cao
Trang chủ / Module 10
🐘 Module 10 / 18 · 4 ngày 📅 Tuần 6 ●●○○ Trung bình

Database và ORM: Drizzle/Prisma, connection pooling, DTO

Chọn ORM, schema và migration, kết nối DB từ môi trường serverless (pooling), singleton khi dev, transaction, DTO và phân trang, và khi nào nên tách backend riêng.

DrizzlePrismaPoolingMigration
📌 Vì sao module này quan trọng

Next.js cho phép truy cập DB ngay trong component, nhưng chạy trên serverless thì mỗi instance mở kết nối riêng — vài trăm instance là hết connection của Postgres. Cấu trúc tầng dữ liệu đúng ngay từ đầu tránh được cả vấn đề hiệu năng lẫn bảo mật.

🎯 Mục tiêu học tập

  • Định nghĩa schema và migration với Drizzle hoặc Prisma
  • Cấu hình kết nối đúng cho serverless và cho server dài hạn
  • Viết truy vấn có transaction, phân trang cursor
  • Trả DTO thay vì bản ghi thô
  • Biết khi nào nên tách backend (NestJS) khỏi Next.js

Drizzle hay Prisma

DrizzlePrisma
Phong cáchGần SQL, schema viết bằng TypeScriptSchema DSL riêng (schema.prisma), API cấp cao
RuntimeMỏng, chạy tốt ở edge/serverlessPrisma 6/7 đã bỏ engine Rust nặng, dùng driver adapter
Migrationdrizzle-kitprisma migrate
Hợp vớiNgười muốn kiểm soát SQLTeam muốn năng suất, tooling (Studio)
// db/schema.ts (Drizzle)
import { pgTable, uuid, text, integer, timestamp, index } from 'drizzle-orm/pg-core';

export const products = pgTable('products', {
  id: uuid('id').primaryKey().defaultRandom(),
  slug: text('slug').notNull().unique(),
  name: text('name').notNull(),
  price: integer('price').notNull(),              // lưu tiền bằng số nguyên (đồng/cent)
  stock: integer('stock').notNull().default(0),
  createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
}, t => [index('products_created_idx').on(t.createdAt)]);

Kết nối: serverless và singleton

// lib/db.ts
import 'server-only';
import { drizzle } from 'drizzle-orm/node-postgres';
import { Pool } from 'pg';

const globalForDb = globalThis as unknown as { pool?: Pool };
const pool = globalForDb.pool ?? new Pool({ connectionString: process.env.DATABASE_URL, max: 5 });
if (process.env.NODE_ENV !== 'production') globalForDb.pool = pool;   // dev: hot reload không mở thêm pool mới

export const db = drizzle(pool, { schema });
  • Serverless (Vercel, Cloud Run scale lớn): dùng pooler phía DB — PgBouncer/Supavisor (transaction mode), Neon pooled URL, Cloud SQL + connector — và max nhỏ cho mỗi instance. Driver HTTP/WebSocket (Neon serverless) cho edge.
  • Server dài hạn (Docker, VM): pool bình thường, đặt max theo công thức (số instance × max ≤ giới hạn DB).
  • Transaction mode của PgBouncer không hỗ trợ prepared statement theo session — cấu hình ORM cho phù hợp.

Truy vấn, transaction, phân trang

// Đặt hàng: trừ kho và tạo đơn trong một transaction, chống bán quá số lượng
export async function placeOrder(userId: string, items: { productId: string; qty: number }[]) {
  return db.transaction(async tx => {
    for (const it of items) {
      const res = await tx.update(products)
        .set({ stock: sql`${products.stock} - ${it.qty}` })
        .where(and(eq(products.id, it.productId), gte(products.stock, it.qty)))   // điều kiện nguyên tử
        .returning({ id: products.id });
      if (res.length === 0) throw new OutOfStockError(it.productId);
    }
    const [order] = await tx.insert(orders).values({ userId, status: 'pending' }).returning();
    await tx.insert(orderItems).values(items.map(i => ({ ...i, orderId: order.id })));
    return order;
  });
}

// Phân trang cursor (ổn định, nhanh với bảng lớn) thay cho OFFSET
export async function listProducts(cursor?: { createdAt: Date; id: string }, limit = 20) {
  return db.select({ id: products.id, name: products.name, price: products.price, createdAt: products.createdAt })
    .from(products)
    .where(cursor ? or(lt(products.createdAt, cursor.createdAt), and(eq(products.createdAt, cursor.createdAt), lt(products.id, cursor.id))) : undefined)
    .orderBy(desc(products.createdAt), desc(products.id))
    .limit(limit + 1);    // lấy thừa 1 để biết còn trang sau
}

DTO: chỉ trả đúng thứ cần

export type PublicUserDTO = { id: string; name: string; avatarUrl: string | null };

export async function getPublicProfile(handle: string): Promise<PublicUserDTO | null> {
  const u = await db.query.users.findFirst({ where: eq(users.handle, handle) });
  if (!u) return null;
  return { id: u.id, name: u.displayName, avatarUrl: u.avatarUrl };   // không có email, hash, role
}

Khi nào tách backend riêng

Giữ trong Next.jsTách backend (NestJS/Go…)
Một web app, một team, logic vừa phảiNhiều client (mobile, đối tác, web khác) dùng chung API
Mutation gắn chặt với giao diệnJob nền nặng, queue, cron, WebSocket lâu dài
Deploy serverless đơn giảnDomain phức tạp cần kiến trúc module, nhiều team backend

Mô hình phổ biến trong JD fullstack: Next.js làm BFF (render, auth phiên, gọi API) + NestJS làm core API; Server Component gọi NestJS qua mạng nội bộ, chia sẻ type/schema qua monorepo.

🚩 Sai lầm hay gặp

  • Tạo new PrismaClient()/new Pool() trong mỗi request.
  • Không dùng pooler khi chạy serverless.
  • Lưu tiền bằng float.
  • Kiểm tra tồn kho rồi mới trừ ở hai câu lệnh riêng (race condition).

🏋️ Bài tập thực hành

Tầng dữ liệu cho cửa hàng

Schema products/orders/order_items với Drizzle, migration, seed 10.000 sản phẩm. Viết placeOrder có transaction và test bắn 50 request đồng thời mua sản phẩm chỉ còn 10 cái — đúng 10 thành công. Phân trang cursor cho trang danh sách, so sánh thời gian với OFFSET ở trang 400.

📚 Tài nguyên học tập

✅ Tự đánh giá hoàn thành

  • Tôi cấu hình kết nối DB đúng cho serverless
  • Tôi viết transaction chống bán quá số lượng
  • Tôi dùng phân trang cursor
  • Tôi trả DTO thay vì bản ghi thô
  • Tôi giải thích được khi nào tách backend riêng