53 lines
1.5 KiB
TypeScript
53 lines
1.5 KiB
TypeScript
import { fail, handleOptions, json } from "../_shared/http.ts";
|
|
import { createServiceClient, requireUser, slugify } 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 { user, error: userError } = await requireUser(req);
|
|
if (!user) return fail(userError ?? "Unauthorized", 401);
|
|
const serviceClient = createServiceClient();
|
|
|
|
let body: { name?: string; slug?: string };
|
|
try {
|
|
body = await req.json();
|
|
} catch {
|
|
return fail("Invalid JSON body");
|
|
}
|
|
|
|
const name = (body.name ?? "").trim();
|
|
if (!name) return fail("name is required");
|
|
|
|
const slug = slugify(body.slug?.trim() || name);
|
|
if (!slug) return fail("slug is invalid");
|
|
|
|
const { data: org, error: createError } = await serviceClient
|
|
.from("organizations")
|
|
.insert({
|
|
name,
|
|
slug,
|
|
owner_user_id: user.id,
|
|
})
|
|
.select("id, name, slug, icon_url, owner_user_id, created_at")
|
|
.single();
|
|
|
|
if (createError) {
|
|
if (createError.code === "23505") return fail("slug is already taken", 409);
|
|
return fail(createError.message, 400);
|
|
}
|
|
|
|
const { error: membershipError } = await serviceClient
|
|
.from("organization_members")
|
|
.insert({
|
|
organization_id: org.id,
|
|
user_id: user.id,
|
|
role: "owner",
|
|
});
|
|
|
|
if (membershipError) return fail(membershipError.message, 400);
|
|
|
|
return json({ organization: org }, 201);
|
|
});
|