ရိုးရိုးလေး ရှင်းပြမယ်
Data layer ကို ရိုးရိုးလေး ပြောရရင်
Data layer ဆိုတာ စာကြည့်တိုက်က စာကြည့်တိုက်မှူး လိုပါပဲ။ Page တွေက စာအုပ်စင်ထဲ ကိုယ်တိုင် ဝင်ရှာမယ့်အစား 'publish လုပ်ထားတဲ့ နောက်ဆုံး note ငါးခု ပေးပါ' လို့ တောင်းပါတယ်။ စာကြည့်တိုက်မှူးက စာအုပ်တွေ ဘယ်မှာ ရှိလဲ၊ သင် ဘာကို ကြည့်ခွင့်ရှိလဲ သိပြီး လိုတဲ့ စာမျက်နှာတွေကိုပဲ ပေးပါတယ်။
Database ကို ပြောင်းရင်၊ စည်းကမ်းအသစ် ထည့်ရင် စာကြည့်တိုက်မှူး တစ်ယောက်တည်းကို ပြောရုံပါပဲ၊ page တိုင်းကို လိုက်ပြင်စရာ မလိုပါဘူး။ Page တွေကလည်း ဘာလိုချင်လဲဆိုတာပဲ ပြောပြီး ဘယ်လို ရှာရမလဲ မပြောရလို့ တိုတိုလေးပဲ ရှိပါတယ်။
Problem → Why → Solution
ပြဿနာ: page တိုင်းမှာ ပြန့်ကျဲနေတဲ့ query တွေ
Page ဆယ့်နှစ်ခုက db.note.findMany(...) ကို ကိုယ်စီ ခေါ်ပြီး filter တွေက နည်းနည်းစီ ကွဲနေပါတယ်။ တစ်ခုက published: true ကို မေ့သွားလို့ draft တွေ public ဖြစ်သွားပါတယ်။ နောက်တစ်ခုက author row တစ်ခုလုံးကို Client Component ဆီ prop အဖြစ် ပေးလိုက်လို့ passwordHash နဲ့ email ပါ page payload ထဲ ရောက်သွားပါတယ်။ Column တစ်ခု နာမည်ပြောင်းရင်လည်း file ဆယ့်နှစ်ခုကို ပြင်ရပါတယ်။
import { db } from "@/lib/db";
import { AuthorCard } from "./author-card"; // a Client Component
export default async function NotePage({ params }) {
const { id } = await params;
const note = await db.note.findUnique({ where: { id }, include: { author: true } });
// drafts are visible, and author.passwordHash is serialized to the browser
return <AuthorCard author={note.author} />;
}စည်းကမ်းကို တစ်နေရာတည်းမှာ ထားရမယ်
'Draft ကို public မပြရ'၊ 'password hash ကို ဘယ်တော့မှ client ဆီ မပို့ရ' လို စည်းကမ်းတွေကို ခေါ်သူတိုင်းက မှတ်ထားရမယ်ဆိုရင် တစ်နေ့ တစ်ယောက်က မေ့သွားမှာ သေချာပါတယ်။ Data layer က အဲဒီ စည်းကမ်းတွေကို database နဲ့ UI ကြားက တစ်ခုတည်းသော တံခါးထဲ ထည့်ပေးပါတယ်။
Core concept: server-only use-case function နဲ့ DTO
Data access layer (DAL) ဆိုတာ lib/data/notes.ts လို server-only module တွေ စုထားတာပါ။ Function တွေကို table နာမည်နဲ့ မဟုတ်ဘဲ use case နဲ့ နာမည်ပေးပါတယ်: getPublishedNotes(), getNoteForEditing(id), createNote(input)။ Page, Server Action နဲ့ Route Handler တွေက ဒီ function တွေကိုပဲ ခေါ်ပြီး database client ကို DAL တစ်ခုတည်းက import လုပ်ပါတယ်။ Next.js ရဲ့ data security guide ကလည်း app အသစ်တွေအတွက် ဒီ ပုံစံကို အကြံပြုပါတယ်။
File ထိပ်က import "server-only" (npm package server-only) က module ကို server သီးသန့်လို့ အမှတ်အသား လုပ်ပါတယ်။ Client Component တစ်ခုက တိုက်ရိုက်ဖြစ်စေ၊ သွယ်ဝိုက်ပြီးဖြစ်စေ import လုပ်မိရင် build က error နဲ့ ရပ်သွားပါတယ်။ ဒါက database URL လို secret တွေနဲ့ ORM code ကို browser bundle ထဲ မရောက်အောင် စောစော ကာကွယ်ပေးပါတယ်။
Server Component ကနေ Client Component ဆီ ပေးတဲ့ prop တွေကို RSC payload ထဲ serialize လုပ်ပြီး browser ဆီ ပို့ပါတယ်။ ဒါကြောင့် DAL က Data Transfer Object (DTO) ကို ပြန်ပေးသင့်ပါတယ်: UI လိုတဲ့ field တွေပဲ ပါတဲ့ object သေးသေးလေးပါ။ ORM မှာ select ကို သုံးရင် database ကနေ ယူတဲ့ data ကိုလည်း လျှော့ပေးပါတယ်။ React ရဲ့ cache() နဲ့ ထုပ်ထားတဲ့ function ကို request တစ်ခုအတွင်း argument တူတူနဲ့ ခေါ်ရင် query က တစ်ခါပဲ run ပါတယ်၊ ဒါကြောင့် layout နဲ့ page နှစ်ခုလုံးက ခေါ်လည်း ကိစ္စမရှိပါဘူး။
Database client ကိုယ်တိုင်ကိုလည်း တစ်ခါပဲ ဖန်တီးရပါမယ်။ Client တစ်ခုက connection pool တစ်ခုကို ဖွင့်ထားပြီး development server က file ပြင်တိုင်း module တွေကို ပြန် run ပါတယ်။ Client ကို globalThis ပေါ်မှာ သိမ်းပြီး ပြန်သုံးတာက ORM တွေရဲ့ docs မှာ ပြထားတဲ့ ပုံမှန် ပုံစံပါ၊ production မှာတော့ module တစ်ခါပဲ load ဖြစ်လို့ မလိုပါဘူး။
| Layer | တာဝန် |
|---|---|
| Page / Server Action | Data ကို တောင်း၊ ပြ ဒါမှမဟုတ် ပြောင်းခိုင်း |
| lib/data (DAL) | Input စစ်၊ permission စစ်၊ query လုပ်၊ DTO ပြန်ပေး |
| lib/db | Database client တစ်ခုကို ဖန်တီးပြီး မျှသုံး |
- Page က use case ကို တောင်း၊ SQL မဟုတ်
- DAL က input နဲ့ permission စစ်
- Query က လိုတဲ့ field ပဲ select
- Typed DTO သေးသေးလေး ပြန်ပေး
Database client ကို import လုပ်တဲ့ file တွေ lib/db နဲ့ lib/data အပြင်မှာ မရှိသင့်ပါဘူး၊ ရှိနေရင် တံခါးကို ကျော်နေတာပါ။
အထွေထွေ ပုံစံ
// lib/data/<resource>.ts
import "server-only";
import { db } from "@/lib/db";
export async function getThingForUi(id: string): Promise<ThingDto | null> {
if (!isValidId(id)) return null; // check input
await assertCanRead(id); // check permission
const row = await db.thing.findFirst({ where: { id }, select: neededFields });
return row ? toDto(row) : null; // only what the UI needs
}Server-only module တစ်ခုထဲမှာ use case တစ်ခုစီအတွက် function တစ်ခု ရေးပြီး input, permission, select, DTO ဆိုတဲ့ အဆင့်တွေကို function ထဲမှာပဲ လုပ်ပါ။
Worked example: notes အတွက် DAL
ပထမ file က database client ကို တစ်ခါပဲ ဖန်တီးပါတယ်။ ဒုတိယ file က page တွေ သုံးမယ့် use case နှစ်ခုကို ပေးပါတယ်။ getNoteById က id နဲ့ row ကို ယူရုံ မဟုတ်ပါဘူး၊ draft တွေ မပေါက်ကြားအောင် published ဖြစ်မဖြစ် စစ်တယ်၊ page လိုအပ်တဲ့ column တွေကိုပဲ select နဲ့ ပြန်ပေးတယ်၊ request တစ်ခုထဲမှာ ထပ်ခေါ်ရင် database ကို တစ်ခါပဲ ရောက်အောင် cache() နဲ့ ထုပ်ထားပါတယ်။
Prisma ကို ဥပမာအဖြစ် သုံးထားပေမဲ့ ပုံစံက Drizzle ဒါမှမဟုတ် SQL client ရိုးရိုးနဲ့လည်း အတူတူပါပဲ။ ORM version အသစ်တွေမှာ client import လုပ်ပုံ ပြောင်းနိုင်လို့ သင့် ORM ရဲ့ Next.js setup guide ကို အရင် စစ်ပါ။ Page တွေက ဒီ file နှစ်ခုရဲ့ export တွေကိုပဲ မြင်ရပါတယ်။
// lib/db.ts (Prisma shown; follow your ORM's documented Next.js setup)
import "server-only";
import { PrismaClient } from "@prisma/client";
const globalForDb = globalThis as unknown as { db?: PrismaClient };
export const db = globalForDb.db ?? new PrismaClient();
if (process.env.NODE_ENV !== "production") globalForDb.db = db;
// lib/data/notes.ts
import "server-only";
import { cache } from "react";
import { db } from "@/lib/db";
export type NoteSummary = { id: string; title: string; updatedAt: Date };
export async function getPublishedNotes(): Promise<NoteSummary[]> {
return db.note.findMany({
where: { published: true },
select: { id: true, title: true, updatedAt: true },
orderBy: { updatedAt: "desc" },
});
}
export const getPublishedNote = cache(async (id: string) => {
if (!id) return null;
return db.note.findFirst({
where: { id, published: true },
select: { id: true, title: true, body: true, updatedAt: true },
});
});Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်
- One client in development
export const db = globalForDb.db ?? new PrismaClient();Development မှာ file ပြင်တိုင်း module တွေ ပြန် run လို့ client အသစ်တွေ (connection pool အသစ်တွေ) မွေးမလာအောင် globalThis ပေါ်မှာ သိမ်းထားပြီး ပြန်သုံးပါတယ်။
- Build-time guard
import "server-only";Client Component က ဒီ file ကို import လုပ်မိရင် build fail ဖြစ်ပါတယ်။ Runtime မှာ secret ပေါက်ကြားတာကို စောင့်မနေရပါဘူး။
- The rule lives here
where: { published: true },'Public list မှာ draft မပါရ' ဆိုတဲ့ စည်းကမ်းက ဒီ line တစ်ကြောင်းတည်းမှာ ရှိပြီး page တွေက မမှတ်ထားရပါဘူး။
- Select is the DTO
select: { id: true, title: true, updatedAt: true },Field သုံးခုပဲ database ကနေ ယူပြီး ပြန်ပေးလို့ return type NoteSummary နဲ့ ကိုက်ညီပါတယ်၊ author email လို field တွေ မပါပါဘူး။
- Deduplicate per request
export const getPublishedNote = cache(async (id: string) => {generateMetadata နဲ့ page နှစ်ခုလုံးက id တူတူနဲ့ ခေါ်ရင် request တစ်ခုအတွင်း query တစ်ခါပဲ run ပါတယ်။
Page တွေက getPublishedNotes() ကို ခေါ်ပြီး id, title, updatedAt ပဲ ရပါတယ်။ Draft တွေ ဘယ်တော့မှ ပြန်မလာဘဲ lib/data/notes.ts ကို Client Component ကနေ import လုပ်ရင် build fail ဖြစ်ပါတယ်။Authorization ကလည်း data layer ထဲမှာ ရှိရမယ်
Edit page အတွက် data ကို ယူတဲ့အခါ 'ဒီ user က ဒီ note ကို ပြင်ခွင့်ရှိလား' ဆိုတာကို function ထဲမှာပဲ စစ်ပါ။ ဒါမှ page အသစ်၊ Route Handler အသစ် ထည့်တဲ့အခါ စစ်ဆေးချက်ကို မမေ့မိမှာပါ။ Query ကိုယ်တိုင်ကို ownerId နဲ့ scope လုပ်ထားရင် တခြားသူရဲ့ id ကို ပေးလည်း null ပဲ ပြန်ရပါတယ်။
Authorization ကို UI မှာ တစ်ခါ၊ data layer မှာ တစ်ခါ စစ်ရတာ ထပ်နေတယ်လို့ ထင်ရနိုင်ပါတယ်။ UI ဘက်က စစ်ဆေးချက်က button ပြမပြ ဆုံးဖြတ်ဖို့ပဲ ဖြစ်ပြီး data layer ဘက်ကမှ တကယ့် အကာအကွယ်ပါ။ Lesson 20 မှာ ဒီ helper တွေကို အသေးစိတ် တည်ဆောက်ပါမယ်။
export async function getNoteForEditing(id: string) {
const user = await getCurrentUser(); // from lib/auth, also server-only
if (!user) return null;
return db.note.findFirst({
where: { id, ownerId: user.id }, // someone else's id finds nothing
select: { id: true, title: true, body: true, published: true },
});
}လက်တွေ့ project တွေမှာ
လက်တွေ့ project တွေမှာ
Project ကြီးလာတာနဲ့အမျှ data layer က ပြောင်းလဲမှုတွေကို တစ်နေရာတည်းမှာ စုပေးပါတယ်။ အောက်က ဥပမာတွေမှာ ပြောင်းလဲမှုက file တစ်ခု နှစ်ခုထဲမှာပဲ ဖြစ်ပြီး page တွေကို မထိရပါဘူး။ ဒါက code review ကိုလည်း အများကြီး လွယ်စေပါတယ်၊ reviewer က စည်းကမ်းအားလုံးကို သိဖို့ DAL ကိုပဲ ဖတ်ရလို့ပါ။
- Soft delete: deletedAt: null ကို DAL function တွေထဲ ထည့်လိုက်ရုံနဲ့ ဖျက်ထားတဲ့ record တွေ app တစ်ခုလုံးကနေ ပျောက်သွားပါတယ်။
- Multi-tenant SaaS: query တိုင်းမှာ tenantId filter ကို DAL က ထည့်ပေးလို့ customer တစ်ယောက်က တခြား customer ရဲ့ data ကို မမြင်ရပါဘူး။
- ORM ပြောင်းခြင်း: Prisma ကနေ Drizzle ကို ပြောင်းတဲ့အခါ function signature တွေ မပြောင်းလို့ lib/data ကိုပဲ ပြန်ရေးရပါတယ်။
- Testing: DAL function တွေကို test database နဲ့ သီးခြား test လုပ်ပြီး component test တွေမှာ fake function နဲ့ အစားထိုးပါတယ်။
အမှားများ
Data layer နဲ့ ဖြစ်လေ့ရှိတဲ့ အမှားများ
ORM client ဒါမှမဟုတ် secret ကို Client Component ထဲ import လုပ်ခြင်း
"use client" file က database module ကို import လုပ်ရင် အကောင်းဆုံးဖြစ်ရင် build fail ဖြစ်ပြီး အဆိုးဆုံးဖြစ်ရင် config တန်ဖိုးတွေ bundle ထဲ ပါသွားပါတယ်။ DAL file တိုင်းမှာ import "server-only" ထည့်ပြီး data ကို Server Component ကနေ prop အဖြစ်ပဲ ပေးပါ။
Field အများကြီးကို select လုပ်ပြီး sensitive data ပါ ပို့ခြင်း
include: { author: true } က passwordHash, email, internal note တွေပါ ယူလာပြီး Client Component ဆီ ပေးလိုက်ရင် view-source နဲ့ မြင်ရပါတယ်။ UI လိုတာကိုပဲ select လုပ်ပါ။
Request တိုင်း ဒါမှမဟုတ် reload တိုင်း client အသစ် ဖန်တီးခြင်း
new PrismaClient() ကို function ထဲမှာ ခေါ်ရင် ဒါမှမဟုတ် development မှာ globalThis ပေါ် မသိမ်းရင် connection တွေ ပြည့်ပြီး 'too many connections' error တက်ပါတယ်။
Filter တွေကို page တွေထဲ ပြန့်ကျဲထားခြင်း
published, tenantId, deletedAt လို filter တွေ page တစ်ခုချင်းထဲမှာ ရှိနေရင် တစ်ခုခုက မေ့ပါလိမ့်မယ်။ အဲဒီ filter တွေကို DAL function ထဲ ရွှေ့ပါ။
Best Practices
Best practices
- Function နာမည်ကို ရလဒ်အတိုင်း ပေးပါ: getPublishedNotes က getNotes ထက် ဘာပြန်ပေးလဲ ပိုရှင်းပါတယ်။
- Return type တွေကို DTO type အဖြစ် ကြေညာပြီး ORM ရဲ့ model type ကို UI ထဲ မပို့ပါနဲ့။
- Mutation function တွေက input object တစ်ခု ယူပြီး လိုအပ်တဲ့ validation ကို ကိုယ်တိုင် လုပ်ပါစေ။
- Request တစ်ခုအတွင်း ခဏခဏ ခေါ်တဲ့ read function တွေကို React cache() နဲ့ ထုပ်ပါ။
Mini challenge
Mini challenge: in-memory data layer
Database row တွေကို array နဲ့ အတုလုပ်ပြီး data layer function သုံးခု ရေးပါ: private field တွေကို ဖယ်တဲ့ toDto၊ userId မရှိရင် query မလုပ်ဘဲ error result ပြန်ပေးတဲ့ getNotesByUser နဲ့ publish လုပ်ထားတဲ့ note ကိုပဲ ပြန်ပေးတဲ့ getPublicNote ပါ။
- toDto က id, title, published ပဲ ပါတဲ့ object ကို ပြန်ပေးရမယ်
- getNotesByUser က userId မရှိ ဒါမှမဟုတ် blank ဖြစ်ရင် { ok: false, error } ပြန်ပေးရမယ်
- getPublicNote က draft id အတွက် null ပြန်ပေးရမယ်
- ownerEmail နဲ့ internalScore တို့ output ထဲမှာ ဘယ်တော့မှ မပေါ်ရဘူး
type NoteRow = {
id: string;
ownerId: string;
title: string;
published: boolean;
ownerEmail: string;
internalScore: number;
};
type NoteDto = { id: string; title: string; published: boolean };
type Result<T> = { ok: true; data: T } | { ok: false; error: string };
const rows: NoteRow[] = [/* TODO: a few rows, published and draft */];
function toDto(row: NoteRow): NoteDto {
// TODO: copy only the fields the UI needs
}
function getNotesByUser(userId: string | undefined): Result<NoteDto[]> {
// TODO: error result for a missing or blank userId, without touching rows
}
function getPublicNote(id: string): NoteDto | null {
// TODO: only published notes are visible to the public
}
// TODO: print a few calls, including a missing userId and a draft idရလဒ်: userId မပါရင် {"ok":false,"error":"userId is required"} ရပါတယ်။ u1 အတွက် note နှစ်ခုကို DTO အဖြစ် ရပြီး draft id က null ဖြစ်ကာ UI ဆီ ရောက်တဲ့ field တွေက id, title, published ပဲ ဖြစ်ပါတယ်။
အရိပ်အမြွက် ကြည့်ရန်
toDto ထဲမှာ { ...row } ကို မသုံးပါနဲ့၊ field တွေကို နာမည်နဲ့ တစ်ခုချင်း ကူးပါ။ ဒါမှ နောက်မှ row ထဲ field အသစ် ထည့်လည်း UI ဆီ အလိုလို မရောက်မှာပါ။
အဖြေ ကြည့်ရန်
type NoteRow = {
id: string;
ownerId: string;
title: string;
published: boolean;
ownerEmail: string;
internalScore: number;
};
type NoteDto = { id: string; title: string; published: boolean };
type Result<T> = { ok: true; data: T } | { ok: false; error: string };
const rows: NoteRow[] = [
{ id: "n1", ownerId: "u1", title: "Hello", published: true,
ownerEmail: "ada@example.com", internalScore: 7 },
{ id: "n2", ownerId: "u1", title: "Draft idea", published: false,
ownerEmail: "ada@example.com", internalScore: 2 },
{ id: "n3", ownerId: "u2", title: "Other user", published: true,
ownerEmail: "bo@example.com", internalScore: 5 },
];
let queries = 0;
function toDto(row: NoteRow): NoteDto {
return { id: row.id, title: row.title, published: row.published };
}
function getNotesByUser(userId: string | undefined): Result<NoteDto[]> {
if (!userId?.trim()) return { ok: false, error: "userId is required" };
queries++;
return { ok: true, data: rows.filter((r) => r.ownerId === userId).map(toDto) };
}
function getPublicNote(id: string): NoteDto | null {
queries++;
const row = rows.find((r) => r.id === id && r.published);
return row ? toDto(row) : null;
}
console.log("getNotesByUser(undefined) ->", JSON.stringify(getNotesByUser(undefined)));
console.log("getNotesByUser(' ') ->", JSON.stringify(getNotesByUser(" ")));
console.log("getNotesByUser('u1') ->", JSON.stringify(getNotesByUser("u1")));
console.log("getPublicNote('n2') ->", JSON.stringify(getPublicNote("n2")));
console.log("getPublicNote('n1') ->", JSON.stringify(getPublicNote("n1")));
console.log("fields sent to the UI:", Object.keys(toDto(rows[0])).join(", "));
console.log("queries run:", queries);Quick Quiz 1 / 3
Quick Quiz 2 / 3
Quick Quiz 3 / 3
မှတ်ထားရမယ့် အချက်များ
- Query တွေကို lib/data ထဲက use-case function တွေအဖြစ် စုပြီး database client ကို DAL ကပဲ import လုပ်ပါ။
- import "server-only" က Client Component ကနေ import လုပ်မိတာကို build အချိန်မှာ ဖမ်းပေးပါတယ်။
- Client Component ဆီ ပေးတဲ့ data ကို serialize လုပ်ပြီး browser ဆီ ပို့လို့ select နဲ့ DTO ကို သုံးပါ။
- Client ကို တစ်ခါပဲ ဖန်တီးပြီး published, tenantId, ownerId လို filter တွေနဲ့ authorization ကို DAL ထဲ ထားပါ။
Next.js — Fetching Data — Next.js
Next.js — Fetching Data — Next.js