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.

Persist avatar to avoid rate limits

Steven Teya9cf2269f4ed
diff --git a/apps/web/app/api/customers/[id]/route.ts b/apps/web/app/api/customers/[id]/route.ts
index ef98e0c4ef..549a1a83be 100644
--- a/apps/web/app/api/customers/[id]/route.ts
+++ b/apps/web/app/api/customers/[id]/route.ts
@@ -4,6 +4,7 @@ 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 { isStored, storage } from "@/lib/storage";
import {
CustomerEnrichedSchema,
CustomerSchema,
@@ -11,7 +12,9 @@ import {
updateCustomerBodySchema,
} from "@/lib/zod/schemas/customers";
import { prisma } from "@dub/prisma";
+import { nanoid, R2_URL } from "@dub/utils";
import { Discount } from "@prisma/client";
+import { waitUntil } from "@vercel/functions";
import { NextResponse } from "next/server";
// GET /api/customers/:id – Get a customer by ID
@@ -99,6 +102,14 @@ export const PATCH = withWorkspace(
},
);
+ // we update the customer avatar if:
+ // 1. it's a new avatar (not stored in R2)
+ // 2. the new avatar is different from the old avatar
+ const updatedCustomerAvatar =
+ avatar && (!isStored(avatar) || avatar !== customer.avatar)
+ ? `${R2_URL}/customers/${customer.id}/avatar_${nanoid(7)}`
+ : undefined;
+
try {
const updatedCustomer = await prisma.customer.update({
where: {
@@ -107,11 +118,29 @@ export const PATCH = withWorkspace(
data: {
name,
email,
- avatar,
+ avatar: updatedCustomerAvatar,
externalId,
},
});
+ if (avatar && updatedCustomerAvatar) {
+ waitUntil(
+ Promise.allSettled([
+ storage.upload(
+ updatedCustomerAvatar.replace(`${R2_URL}/`, ""),
+ avatar,
+ {
+ width: 128,
+ height: 128,
+ },
+ ),
+ customer.avatar &&
+ isStored(customer.avatar) &&
+ storage.delete(customer.avatar.replace(`${R2_URL}/`, "")),
+ ]),
+ );
+ }
+
let discount: Discount | null = null;
if (includeExpandedFields) {
@@ -189,6 +218,10 @@ export const DELETE = withWorkspace(
},
});
+ if (customer.avatar && isStored(customer.avatar)) {
+ storage.delete(customer.avatar.replace(`${R2_URL}/`, ""));
+ }
+
return NextResponse.json({
id: customer.id,
});
diff --git a/apps/web/app/api/customers/route.ts b/apps/web/app/api/customers/route.ts
index 557d925f72..e0f30642a9 100644
--- a/apps/web/app/api/customers/route.ts
+++ b/apps/web/app/api/customers/route.ts
@@ -1,9 +1,11 @@
+import { createId } from "@/lib/api/create-id";
import { determineCustomerDiscount } from "@/lib/api/customers/determine-customer-discount";
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 { generateRandomName } from "@/lib/names";
+import { storage } from "@/lib/storage";
import z from "@/lib/zod";
import {
createCustomerBodySchema,
@@ -13,6 +15,7 @@ import {
} from "@/lib/zod/schemas/customers";
import { DiscountSchemaWithDeprecatedFields } from "@/lib/zod/schemas/discount";
import { prisma } from "@dub/prisma";
+import { nanoid, R2_URL } from "@dub/utils";
import {
Customer,
Discount,
@@ -21,6 +24,7 @@ import {
Program,
ProgramEnrollment,
} from "@prisma/client";
+import { waitUntil } from "@vercel/functions";
import { NextResponse } from "next/server";
interface CustomerResponse extends Customer {
@@ -154,20 +158,38 @@ export const POST = withWorkspace(
await parseRequestBody(req),
);
+ const customerId = createId({ prefix: "cus_" });
const finalCustomerName = name || email || generateRandomName();
+ const finalCustomerAvatar = avatar
+ ? `${R2_URL}/customers/${customerId}/avatar_${nanoid(7)}`
+ : null;
try {
const customer = await prisma.customer.create({
data: {
+ id: customerId,
name: finalCustomerName,
email,
- avatar,
+ avatar: finalCustomerAvatar,
externalId,
projectId: workspace.id,
projectConnectId: workspace.stripeConnectId,
},
});
+ if (avatar && finalCustomerAvatar) {
+ waitUntil(
+ storage.upload(
+ finalCustomerAvatar.replace(`${R2_URL}/`, ""),
+ avatar,
+ {
+ width: 128,
+ height: 128,
+ },
+ ),
+ );
+ }
+
return NextResponse.json(
CustomerSchema.parse(transformCustomer(customer)),
{
diff --git a/apps/web/app/api/track/lead/route.ts b/apps/web/app/api/track/lead/route.ts
index 48ea19d139..220e83fd88 100644
--- a/apps/web/app/api/track/lead/route.ts
+++ b/apps/web/app/api/track/lead/route.ts
@@ -5,6 +5,7 @@ import { parseRequestBody } from "@/lib/api/utils";
import { withWorkspace } from "@/lib/auth";
import { generateRandomName } from "@/lib/names";
import { createPartnerCommission } from "@/lib/partners/create-partner-commission";
+import { isStored, storage } from "@/lib/storage";
import { getClickEvent, recordLead, recordLeadSync } from "@/lib/tinybird";
import { logConversionEvent } from "@/lib/tinybird/log-conversion-events";
import { redis } from "@/lib/upstash";
@@ -240,6 +241,27 @@ export const POST = withWorkspace(
});
}
+ if (customerAvatar && !isStored(customerAvatar)) {
+ // persist customer avatar to R2
+ const { url: persistedAvatarUrl } = await storage.upload(
+ `customers/${customer?.id}/avatar_${nanoid(7)}`,
+ customerAvatar,
+ {
+ width: 128,
+ height: 128,
+ },
+ );
+
+ customer = await prisma.customer.update({
+ where: {
+ id: customer?.id,
+ },
+ data: {
+ avatar: persistedAvatarUrl,
+ },
+ });
+ }
+
await sendWorkspaceWebhook({
trigger: "lead.created",
data: transformLeadEventData({
diff --git a/apps/web/lib/storage.ts b/apps/web/lib/storage.ts
index 8cdcd445a2..ae39d9371f 100644
--- a/apps/web/lib/storage.ts
+++ b/apps/web/lib/storage.ts
@@ -1,4 +1,4 @@
-import { R2_URL, fetchWithTimeout } from "@dub/utils";
+import { OG_AVATAR_URL, R2_URL, fetchWithTimeout } from "@dub/utils";
import { AwsClient } from "aws4fetch";
interface imageOptions {
@@ -151,5 +151,5 @@ class StorageClient {
export const storage = new StorageClient();
export const isStored = (url: string) => {
- return url.startsWith(R2_URL);
+ return url.startsWith(R2_URL) || url.startsWith(OG_AVATAR_URL);
};