Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

1.7 KB
Raw Blame
"use server";

import { db } from "@cap/database";
import { getCurrentUser } from "@cap/database/auth/session";
import { organizations } from "@cap/database/schema";
import type { Organisation } from "@cap/web-domain";
import { eq } from "drizzle-orm";
import { revalidatePath } from "next/cache";
import { requireOrganizationSettingsManager } from "./authorization";

export async function removeOrganizationDomain(
	organizationId: Organisation.OrganisationId,
) {
	const user = await getCurrentUser();

	if (!user) {
		throw new Error("Unauthorized");
	}

	const [organization] = await db()
		.select()
		.from(organizations)
		.where(eq(organizations.id, organizationId));

	if (!organization) throw new Error("Organization not found");

	await requireOrganizationSettingsManager(user.id, organizationId);

	try {
		if (organization.customDomain) {
			const response = await fetch(
				`https://api.vercel.com/v9/projects/${
					process.env.VERCEL_PROJECT_ID
				}/domains/${organization.customDomain.toLowerCase()}?teamId=${
					process.env.VERCEL_TEAM_ID
				}`,
				{
					method: "DELETE",
					headers: {
						Authorization: `Bearer ${process.env.VERCEL_AUTH_TOKEN}`,
					},
				},
			);
			if (!response.ok && response.status !== 404) {
				throw new Error("Failed to remove domain from hosting provider");
			}
		}

		await db()
			.update(organizations)
			.set({
				customDomain: null,
				domainVerified: null,
			})
			.where(eq(organizations.id, organizationId));

		revalidatePath("/dashboard/settings/organization");

		return { success: true };
	} catch (error) {
		if (error instanceof Error) {
			throw new Error(error.message);
		}
		throw new Error("Failed to remove domain");
	}
}