import "server-only"; import { asc, eq, like } from "drizzle-orm"; import { amigoDb } from "@/db/amigo"; import { rak } from "@/db/amigo/schema"; import { PER_PAGE } from "@/lib/pagination"; import { escapeLike } from "@/lib/utils"; export type Rak = { idRak: number; namaRak: string | null; }; export type RakPage = { rows: Rak[]; hasNext: boolean; }; export type RakInput = { namaRak: NonNullable; }; export async function insertRak(input: RakInput): Promise { const [res] = await amigoDb.insert(rak).values({ namaRak: input.namaRak, }); return res.insertId; } export async function updateRak( idRak: number, input: RakInput, ): Promise { const [res] = await amigoDb .update(rak) .set({ namaRak: input.namaRak }) .where(eq(rak.idRak, idRak)); return res.affectedRows > 0; } export async function deleteRak(idRak: number): Promise { const [res] = await amigoDb.delete(rak).where(eq(rak.idRak, idRak)); return res.affectedRows > 0; } export async function listRak(search?: string, page = 1): Promise { const q = search?.trim(); const pattern = q ? `%${escapeLike(q)}%` : ""; const rows = await amigoDb .select({ idRak: rak.idRak, namaRak: rak.namaRak, }) .from(rak) .where(q ? like(rak.namaRak, pattern) : undefined) .orderBy(asc(rak.namaRak), asc(rak.idRak)) .limit(PER_PAGE + 1) .offset((page - 1) * PER_PAGE); return { rows: rows.slice(0, PER_PAGE), hasNext: rows.length > PER_PAGE, }; }