93 lines
2.5 KiB
TypeScript
93 lines
2.5 KiB
TypeScript
import { NextResponse } from "next/server";
|
|
import { createSupabaseRouteClient } from "@/lib/supabase/server";
|
|
import type { MediaAsset } from "@/types/media";
|
|
|
|
export const dynamic = "force-dynamic";
|
|
|
|
export async function GET(request: Request) {
|
|
const supabase = await createSupabaseRouteClient();
|
|
const {
|
|
data: { session },
|
|
} = await supabase.auth.getSession();
|
|
|
|
if (!session) {
|
|
return NextResponse.json({ error: "未登录" }, { status: 401 });
|
|
}
|
|
|
|
const { searchParams } = new URL(request.url);
|
|
const workspaceId = searchParams.get("workspaceId");
|
|
const limit = Number.parseInt(searchParams.get("limit") ?? "12", 10);
|
|
|
|
if (!workspaceId) {
|
|
return NextResponse.json({ error: "缺少 workspaceId" }, { status: 400 });
|
|
}
|
|
|
|
let query = supabase
|
|
.from("media_assets")
|
|
.select("*")
|
|
.eq("workspace_id", workspaceId)
|
|
.order("created_at", { ascending: false })
|
|
.limit(Number.isNaN(limit) ? 12 : limit);
|
|
|
|
const assetType = searchParams.get("assetType");
|
|
if (assetType) {
|
|
query = query.eq("asset_type", assetType);
|
|
}
|
|
|
|
const { data, error } = await query;
|
|
|
|
if (error) {
|
|
return NextResponse.json({ error: error.message }, { status: 500 });
|
|
}
|
|
|
|
return NextResponse.json({ items: (data ?? []) as MediaAsset[] });
|
|
}
|
|
|
|
export async function POST(request: Request) {
|
|
const supabase = await createSupabaseRouteClient();
|
|
const {
|
|
data: { session },
|
|
} = await supabase.auth.getSession();
|
|
|
|
if (!session) {
|
|
return NextResponse.json({ error: "未登录" }, { status: 401 });
|
|
}
|
|
|
|
const payload = (await request.json()) as {
|
|
workspaceId: string;
|
|
documentId: string;
|
|
fileUrl: string;
|
|
thumbnailUrl?: string;
|
|
assetType?: string;
|
|
fileName?: string;
|
|
fileSize?: number;
|
|
mimeType?: string;
|
|
};
|
|
|
|
if (!payload.workspaceId || !payload.documentId || !payload.fileUrl) {
|
|
return NextResponse.json({ error: "参数不完整" }, { status: 400 });
|
|
}
|
|
|
|
const { data, error } = await supabase
|
|
.from("media_assets")
|
|
.insert({
|
|
workspace_id: payload.workspaceId,
|
|
document_id: payload.documentId,
|
|
file_url: payload.fileUrl,
|
|
thumbnail_url: payload.thumbnailUrl ?? payload.fileUrl,
|
|
asset_type: payload.assetType ?? "image",
|
|
file_name: payload.fileName,
|
|
file_size: payload.fileSize ?? null,
|
|
mime_type: payload.mimeType ?? null,
|
|
created_by: session.user.id,
|
|
})
|
|
.select("*")
|
|
.single();
|
|
|
|
if (error) {
|
|
return NextResponse.json({ error: error.message }, { status: 500 });
|
|
}
|
|
|
|
return NextResponse.json({ asset: data as MediaAsset });
|
|
}
|