Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

3.4 KB
Raw Blame
import { handleAndReturnErrorResponse } from "@/lib/api/errors";
import { linkCache } from "@/lib/api/links/cache";
import { qstash } from "@/lib/cron";
import { verifyQstashSignature } from "@/lib/cron/verify-qstash";
import { prisma } from "@/lib/prisma";
import { recordLink } from "@/lib/tinybird";
import { APP_DOMAIN_WITH_NGROK, log, sleep } from "@dub/utils";
import { NextResponse } from "next/server";
import * as z from "zod/v4";
import { sendDomainTransferredEmail } from "./utils";

const schema = z.object({
  currentWorkspaceId: z.string(),
  newWorkspaceId: z.string(),
  domain: z.string(),
});

export const dynamic = "force-dynamic";

export async function POST(req: Request) {
  try {
    const rawBody = await req.text();
    await verifyQstashSignature({ req, rawBody });

    const { currentWorkspaceId, newWorkspaceId, domain } = schema.parse(
      JSON.parse(rawBody),
    );

    const links = await prisma.link.findMany({
      where: { domain, projectId: currentWorkspaceId },
      take: 100,
      orderBy: {
        createdAt: "desc",
      },
    });

    // No remaining links to transfer
    if (!links || links.length === 0) {
      // Send email to the owner of the current workspace
      const linksCount = await prisma.link.count({
        where: { domain, projectId: newWorkspaceId },
      });

      await sendDomainTransferredEmail({
        domain,
        currentWorkspaceId,
        newWorkspaceId,
        linksCount,
      });
    } else {
      // Transfer links to the new workspace
      const linkIds = links.map((link) => link.id);

      await Promise.all([
        prisma.link.updateMany({
          where: {
            domain,
            projectId: currentWorkspaceId,
            id: {
              in: linkIds,
            },
          },
          data: {
            projectId: newWorkspaceId,
            // reset all stats and folder
            clicks: 0,
            leads: 0,
            sales: 0,
            saleAmount: 0,
            conversions: 0,
            lastClicked: null,
            lastLeadAt: null,
            lastConversionAt: null,
            folderId: null,
          },
        }),

        prisma.linkTag.deleteMany({
          where: { linkId: { in: linkIds } },
        }),

        // Update links in redis
        linkCache.mset(
          links.map((link) => ({ ...link, projectId: newWorkspaceId })),
        ),

        // Remove the webhooks associated with the links
        prisma.linkWebhook.deleteMany({
          where: { linkId: { in: linkIds } },
        }),

        // set the links with the old workspace ID to be deleted in Tinybird
        recordLink(links, { deleted: true }),

        // set the links with the new workspace ID to be created in Tinybird
        recordLink(
          links.map((link) => ({
            ...link,
            projectId: newWorkspaceId,
            folderId: null,
          })),
        ),
      ]);

      // wait 500 ms before making another request
      await sleep(500);

      await qstash.publishJSON({
        url: `${APP_DOMAIN_WITH_NGROK}/api/cron/domains/transfer`,
        body: {
          currentWorkspaceId,
          newWorkspaceId,
          domain,
        },
      });
    }

    return NextResponse.json({
      response: "success",
    });
  } catch (error) {
    await log({
      message: `Error transferring domain: ${error.message}`,
      type: "cron",
    });

    return handleAndReturnErrorResponse(error);
  }
}