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.

2.3 KB
Raw Blame
import { prisma } from "@/lib/prisma";
import { Link } from "@prisma/client";
import { DubApiError } from "../errors";
import { prefixWorkspaceId } from "../workspaces/workspace-id";
import {
  decodeLinkIfCaseSensitive,
  encodeKeyIfCaseSensitive,
} from "./case-sensitivity";

interface GetLinkParams {
  workspaceId: string;
  linkId?: string;
  externalId?: string;
  domain?: string;
  key?: string;
  includeUser?: boolean;
  includeWebhooks?: boolean;
}

// Get link or throw error if not found or doesn't belong to workspace
export const getLinkOrThrow = async (params: GetLinkParams) => {
  let {
    workspaceId,
    domain,
    key,
    externalId,
    includeUser = false,
    includeWebhooks = false,
  } = params;
  let link: Link | null = null;

  const linkId = params.linkId || params.externalId || undefined;

  if (domain && (!key || key === "")) {
    key = "_root";
  }

  // Get link by linkId or externalId
  if (linkId) {
    link = await prisma.link.findUnique({
      where: {
        ...(linkId.startsWith("ext_") && workspaceId
          ? {
              projectId_externalId: {
                projectId: workspaceId,
                externalId: linkId.replace("ext_", ""),
              },
            }
          : { id: linkId }),
      },
      include: {
        webhooks: includeWebhooks,
        user: includeUser,
      },
    });
  }

  // Get link by domain and key
  else if (domain && key) {
    key = encodeKeyIfCaseSensitive({
      domain,
      key,
    });

    link = await prisma.link.findUnique({
      where: {
        domain_key: {
          domain,
          key,
        },
      },
      include: {
        webhooks: includeWebhooks,
        user: includeUser,
      },
    });
  }

  if (!link) {
    if (externalId && !externalId.startsWith("ext_")) {
      throw new DubApiError({
        code: "bad_request",
        message: "Invalid externalId. Did you forget to prefix it with `ext_`?",
      });
    }

    throw new DubApiError({
      code: "not_found",
      message: "Link not found.",
    });
  }

  if (link.projectId !== workspaceId) {
    throw new DubApiError({
      code: "unauthorized",
      message: `Link does not belong to workspace ${prefixWorkspaceId(workspaceId)}.`,
    });
  }

  return decodeLinkIfCaseSensitive(link);
};