fix: 데모 화면의 DB 조회·쓰기를 서버 함수로 옮긴다

브라우저가 공개 키로 테이블을 직접 읽고 쓰던 구조를 없앤다.
- api/db.js: 정해진 작업만 서비스 키로 실행 (임의 쿼리·열 지정 불가)
- api/_origin.js: 서버 함수 공용 출처 검사, 공개 배포에서는 404
- src/lib/db.ts: 화면용 호출 함수, 반환 형태 { data, error } 유지
- 빌드 큐에 바로 넣던 예전 진단 신청 모달 삭제

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Haewon KamandClaude Opus 5.5 committed 2026-10-07 16:09:29 +09:00
1 parent b91fdf1a6a
commit 0be730f0f9
14 files changed
+264 -378

No files matched your search

+31
View File
@@ -0,0 +1,31 @@
/**
* 데이터베이스 조회·쓰기. 브라우저는 테이블에 직접 접근하지 않고 서버 함수(api/db.js)의 정해진 작업만 부른다.
* 공개 키로 테이블을 읽고 쓰던 구조를 없애기 위한 것이다 (2026-10-07). 반환 형태는 Supabase 클라이언트와 같은 { data, error }.
*/
export type DbOp =
| 'report.byId' | 'report.status'
| 'run.clinicId' | 'clinic.byId' | 'plan.active' | 'plan.updateEntry'
| 'perf.latest' | 'adjustments.list'
| 'builds.latest' | 'builds.queue' | 'inputs.list' | 'inputs.add';
export interface DbResult<T> {
data: T | null;
error: { message: string; code?: string | null } | null;
}
export async function db<T = unknown>(op: DbOp, params: Record<string, unknown> = {}): Promise<DbResult<T>> {
try {
const res = await fetch('/api/db', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ op, params }),
});
const body = (await res.json().catch(() => null)) as DbResult<T> | null;
if (!body) return { data: null, error: { message: `서버 응답 오류 (${res.status})` } };
return body;
} catch (e) {
console.error(`[db] ${op} 연결 실패`, e);
return { data: null, error: { message: '서버에 연결할 수 없습니다' } };
}
}
+12 -45
View File
@@ -1,9 +1,10 @@
import { createClient } from "@supabase/supabase-js";
import { db } from "./db";
const supabaseUrl = import.meta.env.VITE_SUPABASE_URL;
const supabaseAnonKey = import.meta.env.VITE_SUPABASE_ANON_KEY;
export const supabase = createClient(supabaseUrl, supabaseAnonKey);
// 테이블 조회·쓰기는 서버 함수(api/db.js)를 거친다 (src/lib/db.ts). 브라우저에는 테이블 권한이 없다.
// 아래 주소와 공개 키는 Edge Function 호출(fnHeaders)에만 쓴다.
/** Common headers for Edge Function calls (includes JWT auth) */
const fnHeaders = () => ({
@@ -29,11 +30,8 @@ export async function generateMarketingReport(url: string, clinicName?: string)
}
export async function fetchReportById(reportId: string) {
const { data, error } = await supabase
.from("marketing_reports")
.select("*")
.eq("id", reportId)
.single();
// 예전 Supabase 클라이언트처럼 행 형태를 호출하는 쪽이 정한다.
const { data, error } = await db<any>("report.byId", { id: reportId });
if (error) throw new Error(`Failed to fetch report: ${error.message}`);
return data;
@@ -54,11 +52,10 @@ export interface PipelineStatus {
}
export async function fetchPipelineStatus(reportId: string): Promise<PipelineStatus> {
const { data, error } = await supabase
.from("marketing_reports")
.select("id, status, clinic_name, channel_data, report")
.eq("id", reportId)
.single();
const { data, error } = await db<{
id: string; status: string | null; clinic_name?: string;
channel_data: Record<string, unknown> | null; report: Record<string, unknown> | null;
}>("report.status", { id: reportId });
if (error || !data) throw new Error(`Report not found: ${error?.message}`);
@@ -240,14 +237,7 @@ export async function generateContentPlan(reportId: string, clinicId?: string, r
* Returns the most recent is_active=true plan with all JSONB columns.
*/
export async function fetchActiveContentPlan(clinicId: string) {
const { data, error } = await supabase
.from("content_plans")
.select("*")
.eq("clinic_id", clinicId)
.eq("is_active", true)
.order("created_at", { ascending: false })
.limit(1)
.single();
const { data, error } = await db<any>("plan.active", { clinicId });
if (error) return null;
return data;
@@ -262,31 +252,8 @@ export async function updateCalendarEntry(
entryId: string,
updates: Record<string, unknown>,
) {
// Read current calendar
const { data: plan, error: readErr } = await supabase
.from("content_plans")
.select("calendar")
.eq("id", planId)
.single();
if (readErr || !plan) throw new Error(`Plan not found: ${readErr?.message}`);
const calendar = plan.calendar as { weeks: { entries: Record<string, unknown>[] }[] };
// Find and update entry
for (const week of calendar.weeks) {
for (let i = 0; i < week.entries.length; i++) {
if (week.entries[i].id === entryId) {
week.entries[i] = { ...week.entries[i], ...updates, isManualEdit: true };
break;
}
}
}
const { error: writeErr } = await supabase
.from("content_plans")
.update({ calendar })
.eq("id", planId);
// 읽기·수정·저장을 서버 함수가 한 번에 한다.
const { error: writeErr } = await db("plan.updateEntry", { planId, entryId, updates });
if (writeErr) throw new Error(`Update failed: ${writeErr.message}`);
}