66 lines
1.9 KiB
JavaScript
66 lines
1.9 KiB
JavaScript
import {
|
|
createServerSupabaseClient,
|
|
getAuthenticatedUser,
|
|
} from "@/lib/supabase/server.js";
|
|
|
|
const SCHEMA = "confidence_engine";
|
|
const TABLE = "investigations";
|
|
|
|
async function getAuthenticatedPersistenceContext() {
|
|
const user = await getAuthenticatedUser();
|
|
if (!user) return null;
|
|
return { user, supabase: createServerSupabaseClient() };
|
|
}
|
|
|
|
function throwIfDatabaseError(error) {
|
|
if (error) throw new Error("Investigation persistence request failed");
|
|
}
|
|
|
|
export async function saveInvestigation(snapshot, id = snapshot?.id) {
|
|
if (!snapshot || typeof snapshot !== "object" || !id) {
|
|
throw new Error("Investigation snapshot and id are required");
|
|
}
|
|
const context = await getAuthenticatedPersistenceContext();
|
|
if (!context) return null;
|
|
|
|
const { data, error } = await context.supabase
|
|
.schema(SCHEMA)
|
|
.from(TABLE)
|
|
.upsert({ id, user_id: context.user.id, snapshot }, { onConflict: "id" })
|
|
.select("id, snapshot, created_at, updated_at")
|
|
.single();
|
|
throwIfDatabaseError(error);
|
|
return data?.snapshot ?? null;
|
|
}
|
|
|
|
export async function loadInvestigation(id) {
|
|
if (!id) return null;
|
|
const context = await getAuthenticatedPersistenceContext();
|
|
if (!context) return null;
|
|
|
|
const { data, error } = await context.supabase
|
|
.schema(SCHEMA)
|
|
.from(TABLE)
|
|
.select("snapshot")
|
|
.eq("id", id)
|
|
.maybeSingle();
|
|
throwIfDatabaseError(error);
|
|
return data?.snapshot ?? null;
|
|
}
|
|
|
|
export async function listInvestigations() {
|
|
const context = await getAuthenticatedPersistenceContext();
|
|
if (!context) return null;
|
|
|
|
const { data, error } = await context.supabase
|
|
.schema(SCHEMA)
|
|
.from(TABLE)
|
|
.select("id, created_at, updated_at")
|
|
.order("updated_at", { ascending: false });
|
|
throwIfDatabaseError(error);
|
|
return (data ?? []).map((record) => ({
|
|
id: record.id,
|
|
createdAt: record.created_at,
|
|
updatedAt: record.updated_at,
|
|
}));
|
|
} |