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.

fix ExtendedWorkspaceProps + tests

Steven Teyc8e8a800b915
diff --git a/apps/web/app/(ee)/api/cron/link-retention-cleanup/route.ts b/apps/web/app/(ee)/api/cron/link-retention-cleanup/route.ts
index 4ffe8bd9d5..4f4218ad6b 100644
--- a/apps/web/app/(ee)/api/cron/link-retention-cleanup/route.ts
+++ b/apps/web/app/(ee)/api/cron/link-retention-cleanup/route.ts
@@ -2,6 +2,7 @@ import { handleAndReturnErrorResponse } from "@/lib/api/errors";
import { verifyVercelSignature } from "@/lib/cron/verify-vercel";
import { recordLinkTB, transformLinkTB } from "@/lib/tinybird";
import { prisma } from "@dub/prisma";
+import { Domain } from "@prisma/client";
import { NextResponse } from "next/server";
export const dynamic = "force-dynamic";
@@ -23,14 +24,11 @@ export async function GET(req: Request) {
id: true,
slug: true,
linkRetentionDays: true,
+ projectId: true,
},
});
- await Promise.all(
- domains.map((domain) =>
- deleteOldLinks(domain.slug, domain.linkRetentionDays!),
- ),
- );
+ await Promise.all(domains.map((domain) => deleteOldLinks(domain)));
return NextResponse.json("OK");
} catch (error) {
@@ -41,15 +39,21 @@ export async function GET(req: Request) {
const LINKS_PER_BATCH = 100;
const MAX_LINK_BATCHES = 10;
-async function deleteOldLinks(domain: string, linkRetentionDays: number) {
+async function deleteOldLinks(
+ domain: Pick<Domain, "id" | "slug" | "linkRetentionDays" | "projectId">,
+) {
+ if (!domain.linkRetentionDays || !domain.projectId) return;
+
let processedBatches = 0;
while (processedBatches < MAX_LINK_BATCHES) {
const links = await prisma.link.findMany({
where: {
- domain,
+ domain: domain.slug,
createdAt: {
- lt: new Date(Date.now() - 1000 * 60 * 60 * 24 * linkRetentionDays),
+ lt: new Date(
+ Date.now() - 1000 * 60 * 60 * 24 * domain.linkRetentionDays,
+ ),
},
linkRetentionCleanupDisabledAt: null,
},
@@ -65,15 +69,32 @@ async function deleteOldLinks(domain: string, linkRetentionDays: number) {
`[Link retention cleanup] Deleting ${links.length} links for ${domain} (batch ${processedBatches + 1})...`,
);
- await prisma.link.deleteMany({
- where: {
- id: {
- in: links.map(({ id }) => id),
+ console.table(links, ["shortLink", "createdAt"]);
+
+ await prisma.$transaction(async (tx) => {
+ await tx.link.deleteMany({
+ where: {
+ id: {
+ in: links.map(({ id }) => id),
+ },
},
- },
+ });
+ await tx.project.update({
+ where: {
+ id: domain.projectId!,
+ },
+ data: {
+ totalLinks: { decrement: links.length },
+ },
+ });
});
- // Record the links deletion in Tinybird
- // not 100% sure if we need this yet, maybe we should just delete the link completely from TB to save space?
+
+ console.log(
+ `[Link retention cleanup] Deleted ${links.length} links for ${domain}!`,
+ );
+
+ // // Record the links deletion in Tinybird
+ // // not 100% sure if we need this yet, maybe we should just delete the link completely from TB to save space?
await recordLinkTB(
links.map((link) => ({
...transformLinkTB(link),
diff --git a/apps/web/app/api/workspaces/[idOrSlug]/route.ts b/apps/web/app/api/workspaces/[idOrSlug]/route.ts
index 84d27f2b9b..f6d4e731a8 100644
--- a/apps/web/app/api/workspaces/[idOrSlug]/route.ts
+++ b/apps/web/app/api/workspaces/[idOrSlug]/route.ts
@@ -25,9 +25,11 @@ export const GET = withWorkspace(
projectId: workspace.id,
},
select: {
+ id: true,
slug: true,
primary: true,
verified: true,
+ linkRetentionDays: true,
},
take: 100,
});
diff --git a/apps/web/lib/swr/use-workspace.ts b/apps/web/lib/swr/use-workspace.ts
index 2514bca687..49db0f053c 100644
--- a/apps/web/lib/swr/use-workspace.ts
+++ b/apps/web/lib/swr/use-workspace.ts
@@ -1,4 +1,4 @@
-import { ExpandedWorkspaceProps } from "@/lib/types";
+import { ExtendedWorkspaceProps } from "@/lib/types";
import { PRO_PLAN, fetcher, getNextPlan } from "@dub/utils";
import { useParams, useSearchParams } from "next/navigation";
import useSWR, { SWRConfiguration } from "swr";
@@ -18,7 +18,7 @@ export default function useWorkspace({
data: workspace,
error,
mutate,
- } = useSWR<ExpandedWorkspaceProps>(
+ } = useSWR<ExtendedWorkspaceProps>(
slug && `/api/workspaces/${slug}`,
fetcher,
{
diff --git a/apps/web/lib/types.ts b/apps/web/lib/types.ts
index add879f62d..875288307b 100644
--- a/apps/web/lib/types.ts
+++ b/apps/web/lib/types.ts
@@ -160,7 +160,6 @@ export interface WorkspaceProps extends Project {
logo: string | null;
plan: PlanProps;
domains: {
- id: string;
slug: string;
primary: boolean;
verified: boolean;
@@ -175,13 +174,16 @@ export interface WorkspaceProps extends Project {
store: Record<string, any> | null;
}
-export type ExpandedWorkspaceProps = WorkspaceProps & {
+export interface ExtendedWorkspaceProps extends WorkspaceProps {
+ domains: (WorkspaceProps["domains"][number] & {
+ linkRetentionDays: number | null;
+ })[];
defaultProgramId: string | null;
allowedHostnames: string[];
users: (WorkspaceProps["users"][number] & {
workspacePreferences?: z.infer<typeof workspacePreferencesSchema>;
})[];
-};
+}
export type WorkspaceWithUsers = Omit<WorkspaceProps, "domains">;
diff --git a/apps/web/lib/zod/schemas/workspaces.ts b/apps/web/lib/zod/schemas/workspaces.ts
index 5fe368caaf..71d8b94c4f 100644
--- a/apps/web/lib/zod/schemas/workspaces.ts
+++ b/apps/web/lib/zod/schemas/workspaces.ts
@@ -160,6 +160,11 @@ export const notificationTypes = z.enum([
]);
export const WorkspaceSchemaExtended = WorkspaceSchema.extend({
+ domains: z.array(
+ WorkspaceSchema.shape.domains.element.extend({
+ linkRetentionDays: z.number().nullish(),
+ }),
+ ),
defaultProgramId: z.string().nullable(),
users: z.array(
WorkspaceSchema.shape.users.element.extend({
diff --git a/apps/web/tests/utils/schema.ts b/apps/web/tests/utils/schema.ts
index 9d8a0e955f..6ce79adfb0 100644
--- a/apps/web/tests/utils/schema.ts
+++ b/apps/web/tests/utils/schema.ts
@@ -58,6 +58,7 @@ export const expectedLink: Partial<Link> & {
testCompletedAt: null,
testStartedAt: null,
testVariants: null,
+ linkRetentionCleanupDisabledAt: null,
};
export const expectedTag: Partial<Tag> = {
diff --git a/apps/web/ui/links/link-builder/more-dropdown.tsx b/apps/web/ui/links/link-builder/more-dropdown.tsx
index 96bef01327..27b0ca1825 100644
--- a/apps/web/ui/links/link-builder/more-dropdown.tsx
+++ b/apps/web/ui/links/link-builder/more-dropdown.tsx
@@ -1,4 +1,3 @@
-import useDomains from "@/lib/swr/use-domains";
import useWorkspace from "@/lib/swr/use-workspace";
import { useABTestingModal } from "@/ui/modals/link-builder/ab-testing-modal";
import { useAdvancedModal } from "@/ui/modals/link-builder/advanced-modal";
@@ -17,15 +16,13 @@ import { LinkFormData } from "./link-builder-provider";
import { useLinkBuilderKeyboardShortcut } from "./use-link-builder-keyboard-shortcut";
export function MoreDropdown() {
- const { flags, defaultProgramId } = useWorkspace();
+ const { domains, flags, defaultProgramId } = useWorkspace();
const { isMobile } = useMediaQuery();
const [openPopover, setOpenPopover] = useState(false);
const { watch, setValue } = useFormContext<LinkFormData>();
const data = watch();
- const { allWorkspaceDomains } = useDomains();
-
const options = useMemo(() => {
return [...(isMobile ? MOBILE_MORE_ITEMS : []), ...MORE_ITEMS].filter(
(option) => {
@@ -33,14 +30,13 @@ export function MoreDropdown() {
if (option.key === "partnerId") return Boolean(defaultProgramId);
if (option.key === "linkRetentionCleanupDisabledAt")
return Boolean(
- allWorkspaceDomains.find((d) => d.slug === data.domain)
- ?.linkRetentionDays,
+ domains?.find((d) => d.slug === data.domain)?.linkRetentionDays,
);
return true;
},
);
- }, [data, isMobile, flags, defaultProgramId, allWorkspaceDomains]);
+ }, [data, isMobile, domains, flags, defaultProgramId]);
const { ABTestingModal, setShowABTestingModal } = useABTestingModal();
const { PasswordModal, setShowPasswordModal } = usePasswordModal();
@@ -90,7 +86,7 @@ export function MoreDropdown() {
<Popover
align="start"
content={
- <div className="grid p-1 max-sm:w-full md:min-w-72">
+ <div className="grid p-1 max-sm:w-full md:min-w-80">
{options.map((option) => {
const enabled =
"enabled" in option && typeof option.enabled === "function"
@@ -138,13 +134,15 @@ export function MoreDropdown() {
{option.label}
</>
)}
- {option.description && option.learnMoreUrl && (
+ {option.description && (
<ProBadgeTooltip
content={
<SimpleTooltipContent
title={option.description}
- cta="Learn more."
- href={option.learnMoreUrl}
+ {...(option.learnMoreUrl && {
+ cta: "Learn more.",
+ href: option.learnMoreUrl,
+ })}
/>
}
/>
diff --git a/packages/ui/src/tooltip.tsx b/packages/ui/src/tooltip.tsx
index 445adaea98..41dfdcaa3d 100644
--- a/packages/ui/src/tooltip.tsx
+++ b/packages/ui/src/tooltip.tsx
@@ -133,21 +133,26 @@ export function SimpleTooltipContent({
href,
}: {
title: string;
- cta: string;
- href: string;
+ cta?: string;
+ href?: string;
}) {
return (
<div className="max-w-xs px-4 py-2 text-center text-sm text-neutral-700">
- {title}{" "}
- <a
- href={href}
- target="_blank"
- rel="noopener noreferrer"
- onClick={(e) => e.stopPropagation()}
- className="inline-flex text-neutral-500 underline underline-offset-4 hover:text-neutral-800"
- >
- {cta}
- </a>
+ {title}
+ {cta && href && (
+ <>
+ {" "}
+ <a
+ href={href}
+ target="_blank"
+ rel="noopener noreferrer"
+ onClick={(e) => e.stopPropagation()}
+ className="inline-flex text-neutral-500 underline underline-offset-4 hover:text-neutral-800"
+ >
+ {cta}
+ </a>
+ </>
+ )}
</div>
);
}