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.

1.9 KB
Raw Blame
import { prisma } from "@/lib/prisma";
import { getCustomersQuerySchemaExtended } from "@/lib/zod/schemas/customers";
import * as z from "zod/v4";
import { DubApiError } from "../../api/errors";
import { buildPaginationQuery } from "../../api/pagination";
import { buildCustomerSearchWhere } from "./customer-count-where";

type GetCustomersInput = z.infer<typeof getCustomersQuerySchemaExtended> & {
  workspaceId: string;
};

export async function getCustomers(filters: GetCustomersInput) {
  const {
    customerIds,
    workspaceId,
    email,
    externalId,
    search,
    country,
    linkId,
    includeExpandedFields,
    startingAfter,
    endingBefore,
  } = filters;

  const paginationQuery = buildPaginationQuery(filters);

  // Validate the provided cursor ID
  const cursorId = startingAfter || endingBefore;

  if (cursorId) {
    const customer = await prisma.customer.findUnique({
      where: {
        id: cursorId,
      },
      select: {
        id: true,
        projectId: true,
      },
    });

    if (!customer || customer.projectId !== workspaceId) {
      throw new DubApiError({
        code: "unprocessable_entity",
        message: "Invalid cursor: the provided ID does not exist.",
      });
    }
  }

  return await prisma.customer.findMany({
    where: {
      ...(customerIds
        ? {
            id: { in: customerIds },
          }
        : {}),
      projectId: workspaceId,
      ...buildCustomerSearchWhere({ email, externalId, search }),
      ...(country && {
        country,
      }),
      ...(linkId && {
        linkId,
      }),
    },
    ...paginationQuery,
    ...(includeExpandedFields
      ? {
          include: {
            link: {
              select: {
                id: true,
                domain: true,
                key: true,
                shortLink: true,
                url: true,
              },
            },
          },
        }
      : {}),
  });
}