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.8 KB
Raw Blame
import { createId } from "@/lib/api/create-id";
import { transformCustomer } from "@/lib/api/customers/transform-customer";
import { DubApiError } from "@/lib/api/errors";
import { parseRequestBody } from "@/lib/api/utils";
import { withWorkspace } from "@/lib/auth";
import { getCustomers } from "@/lib/customers/api/get-customers";
import { getNormalizedEmail } from "@/lib/email/normalize-email";
import { generateRandomName } from "@/lib/names";
import { prisma } from "@/lib/prisma";
import { isStored, storage } from "@/lib/storage";
import {
  createCustomerBodySchema,
  CustomerEnrichedSchema,
  CustomerSchema,
  getCustomersQuerySchemaExtended,
} from "@/lib/zod/schemas/customers";
import { nanoid, R2_URL } from "@dub/utils";
import { waitUntil } from "@vercel/functions";
import { NextResponse } from "next/server";

// GET /api/customers – Get all customers
export const GET = withWorkspace(
  async ({ workspace, searchParams }) => {
    const filters = getCustomersQuerySchemaExtended.parse(searchParams);

    const { includeExpandedFields } = filters;

    const customers = await getCustomers({
      ...filters,
      workspaceId: workspace.id,
    });

    const responseSchema = includeExpandedFields
      ? CustomerEnrichedSchema
      : CustomerSchema;

    const response = responseSchema
      .array()
      .parse(customers.map(transformCustomer));

    return NextResponse.json(response);
  },
  {
    requiredPermissions: ["customers.read"],
    requiredPlan: ["business", "advanced", "enterprise"],
  },
);

// POST /api/customers – Create a customer
export const POST = withWorkspace(
  async ({ req, workspace }) => {
    const { email, name, avatar, externalId, stripeCustomerId, country } =
      createCustomerBodySchema.parse(await parseRequestBody(req));

    const customerId = createId({ prefix: "cus_" });
    const finalCustomerName = name || email || generateRandomName();
    const finalCustomerAvatar =
      avatar && !isStored(avatar)
        ? `${R2_URL}/customers/${customerId}/avatar_${nanoid(7)}`
        : avatar;

    try {
      const customer = await prisma.customer.create({
        data: {
          id: customerId,
          name: finalCustomerName,
          email,
          normalizedEmail: getNormalizedEmail(email),
          avatar: finalCustomerAvatar,
          externalId,
          stripeCustomerId,
          country,
          projectId: workspace.id,
          projectConnectId: workspace.stripeConnectId,
        },
      });

      if (avatar && !isStored(avatar) && finalCustomerAvatar) {
        waitUntil(
          storage
            .upload({
              key: finalCustomerAvatar.replace(`${R2_URL}/`, ""),
              body: avatar,
              opts: {
                width: 128,
                height: 128,
              },
            })
            .catch(async (error) => {
              console.error("Error persisting customer avatar to R2", error);
              // if the avatar fails to upload to R2, set the avatar to null in the database
              await prisma.customer.update({
                where: {
                  id: customer.id,
                },
                data: {
                  avatar: null,
                },
              });
            }),
        );
      }

      return NextResponse.json(
        CustomerSchema.parse(transformCustomer(customer)),
        {
          status: 201,
        },
      );
    } catch (error) {
      if (error.code === "P2002") {
        throw new DubApiError({
          code: "conflict",
          message: "A customer with this external ID already exists.",
        });
      }

      throw new DubApiError({
        code: "unprocessable_entity",
        message: error.message,
      });
    }
  },
  {
    requiredPermissions: ["customers.write"],
    requiredPlan: ["business", "advanced", "enterprise"],
  },
);