Roadbound-BRR/supabase/functions/channel-list/index.ts

42 lines
1.3 KiB
TypeScript

import { fail, handleOptions, json } from "../_shared/http.ts";
import { requireUser } from "../_shared/supabase.ts";
Deno.serve(async (req) => {
const preflight = handleOptions(req);
if (preflight) return preflight;
if (req.method !== "POST") return fail("Method not allowed", 405);
const { client, user, error: userError } = await requireUser(req);
if (!user) return fail(userError ?? "Unauthorized", 401);
let body: { organization_id?: string };
try {
body = await req.json();
} catch {
return fail("Invalid JSON body");
}
const organizationId = body.organization_id;
if (!organizationId) return fail("organization_id is required");
const { data: membership, error: membershipError } = await client
.from("organization_members")
.select("organization_id")
.eq("organization_id", organizationId)
.eq("user_id", user.id)
.maybeSingle();
if (membershipError) return fail(membershipError.message, 400);
if (!membership) return fail("forbidden", 403);
const { data: channels, error } = await client
.from("channels")
.select("id, organization_id, name, description, slug, type, topic, is_private, position, created_at")
.eq("organization_id", organizationId)
.order("position", { ascending: true });
if (error) return fail(error.message, 400);
return json({ channels: channels ?? [] });
});