Skip to content

Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.

Optimize datarooms list endpoint

Cursor Agent2d04798accdb
diff --git a/components/datarooms/dataroom-card.tsx b/components/datarooms/dataroom-card.tsx
index f63f35b9..a67fcdba 100644
--- a/components/datarooms/dataroom-card.tsx
+++ b/components/datarooms/dataroom-card.tsx
@@ -17,17 +17,6 @@ import {
TooltipTrigger,
} from "@/components/ui/tooltip";
-type DataroomLink = {
- id: string;
- isArchived: boolean;
- expiresAt: Date | null;
- createdAt: Date;
-};
-
-type DataroomView = {
- viewedAt: Date;
-};
-
type DataroomTag = {
tag: {
id: string;
@@ -44,8 +33,8 @@ type DataroomWithDetails = {
documents: number;
views: number;
};
- links: DataroomLink[];
- views: DataroomView[];
+ activeLinkCount: number;
+ lastViewedAt: Date | null;
createdAt: Date;
tags?: DataroomTag[];
};
@@ -57,16 +46,9 @@ interface DataroomCardProps {
export default function DataroomCard({ dataroom }: DataroomCardProps) {
const router = useRouter();
- // Calculate active links
- const activeLinks = dataroom.links.filter((link) => {
- if (link.isArchived) return false;
- if (link.expiresAt && new Date(link.expiresAt) < new Date()) return false;
- return true;
- });
-
- const isActive = activeLinks.length > 0;
- const activeLinkCount = activeLinks.length;
- const lastViewedAt = dataroom.views[0]?.viewedAt;
+ const isActive = dataroom.activeLinkCount > 0;
+ const activeLinkCount = dataroom.activeLinkCount;
+ const lastViewedAt = dataroom.lastViewedAt;
const hasDocuments = dataroom._count.documents > 0;
const handleButtonClick = (e: React.MouseEvent) => {
diff --git a/lib/swr/use-datarooms.ts b/lib/swr/use-datarooms.ts
index 85e54770..71b8fb35 100644
--- a/lib/swr/use-datarooms.ts
+++ b/lib/swr/use-datarooms.ts
@@ -6,20 +6,13 @@ import useSWR from "swr";
import { fetcher } from "@/lib/utils";
-export type DataroomWithCount = Dataroom & {
+export type DataroomWithCount = Pick<Dataroom, "id" | "name" | "createdAt"> & {
_count: {
documents: number;
views: number;
};
- links: {
- id: string;
- isArchived: boolean;
- expiresAt: Date | null;
- createdAt: Date;
- }[];
- views: {
- viewedAt: Date;
- }[];
+ activeLinkCount: number;
+ lastViewedAt: Date | null;
tags?: {
tag: {
id: string;
diff --git a/pages/api/teams/[teamId]/datarooms/index.ts b/pages/api/teams/[teamId]/datarooms/index.ts
index 89e1bb13..2a9e010b 100644
--- a/pages/api/teams/[teamId]/datarooms/index.ts
+++ b/pages/api/teams/[teamId]/datarooms/index.ts
@@ -3,6 +3,7 @@ import { NextApiRequest, NextApiResponse } from "next";
import { isTeamPausedById } from "@/ee/features/billing/cancellation/lib/is-team-paused";
import { getLimits } from "@/ee/limits/server";
import { authOptions } from "@/pages/api/auth/[...nextauth]";
+import { Prisma } from "@prisma/client";
import slugify from "@sindresorhus/slugify";
import { getServerSession } from "next-auth/next";
@@ -50,15 +51,16 @@ export default async function handle(
return res.status(401).end("Unauthorized");
}
- // Get total unfiltered count first
- const totalCount = await prisma.dataroom.count({
- where: {
- teamId: teamId,
- },
- });
+ const now = new Date();
+ const activeLinkFilter: Prisma.LinkWhereInput = {
+ linkType: "DATAROOM_LINK",
+ deletedAt: null,
+ isArchived: false,
+ OR: [{ expiresAt: null }, { expiresAt: { gte: now } }],
+ };
// Build where clause based on filters
- const whereClause: any = {
+ const whereClause: Prisma.DataroomWhereInput = {
teamId: teamId,
};
@@ -86,78 +88,89 @@ export default async function handle(
}
}
- // Check if the user is part of the team
- const datarooms = await prisma.dataroom.findMany({
- where: whereClause,
- include: {
- _count: {
- select: { documents: true, views: true },
- },
- links: {
- where: {
- linkType: "DATAROOM_LINK",
- deletedAt: null,
- },
- orderBy: {
- createdAt: "desc",
- },
- select: {
- id: true,
- isArchived: true,
- expiresAt: true,
- createdAt: true,
- },
+ if (status === "active") {
+ whereClause.links = { some: activeLinkFilter };
+ } else if (status === "inactive") {
+ whereClause.links = { none: activeLinkFilter };
+ }
+
+ const [totalCount, datarooms] = await Promise.all([
+ prisma.dataroom.count({
+ where: {
+ teamId: teamId,
},
- views: {
- orderBy: {
- viewedAt: "desc",
- },
- take: 1,
- select: {
- viewedAt: true,
+ }),
+ prisma.dataroom.findMany({
+ where: whereClause,
+ select: {
+ id: true,
+ name: true,
+ createdAt: true,
+ _count: {
+ select: { documents: true, views: true },
},
- },
- tags: {
- include: {
- tag: {
- select: {
- id: true,
- name: true,
- color: true,
- description: true,
+ tags: {
+ include: {
+ tag: {
+ select: {
+ id: true,
+ name: true,
+ color: true,
+ description: true,
+ },
},
},
},
},
- },
- orderBy: {
- createdAt: "desc",
- },
- });
+ orderBy: {
+ createdAt: "desc",
+ },
+ }),
+ ]);
+
+ const dataroomIds = datarooms.map((dataroom) => dataroom.id);
+ const [activeLinkCounts, lastViewedAtByDataroom] = dataroomIds.length
+ ? await Promise.all([
+ prisma.link.groupBy({
+ by: ["dataroomId"],
+ where: {
+ dataroomId: { in: dataroomIds },
+ ...activeLinkFilter,
+ },
+ _count: {
+ _all: true,
+ },
+ }),
+ prisma.view.groupBy({
+ by: ["dataroomId"],
+ where: {
+ dataroomId: { in: dataroomIds },
+ },
+ _max: {
+ viewedAt: true,
+ },
+ }),
+ ])
+ : [[], []];
- // Status filter (applied after fetching since it's computed)
- let filteredDatarooms = datarooms;
- if (status) {
- filteredDatarooms = datarooms.filter((dataroom) => {
- const activeLinks = dataroom.links.filter((link) => {
- if (link.isArchived) return false;
- if (link.expiresAt && new Date(link.expiresAt) < new Date())
- return false;
- return true;
- });
- const isActive = activeLinks.length > 0;
+ const activeLinkCountMap = new Map(
+ activeLinkCounts.map((entry) => [entry.dataroomId, entry._count._all]),
+ );
+ const lastViewedAtMap = new Map(
+ lastViewedAtByDataroom.map((entry) => [
+ entry.dataroomId,
+ entry._max.viewedAt,
+ ]),
+ );
- if (status === "active") {
- return isActive;
- } else if (status === "inactive") {
- return !isActive;
- }
- return true;
- });
- }
+ const dataroomsWithStats = datarooms.map((dataroom) => ({
+ ...dataroom,
+ activeLinkCount: activeLinkCountMap.get(dataroom.id) ?? 0,
+ lastViewedAt: lastViewedAtMap.get(dataroom.id) ?? null,
+ }));
return res.status(200).json({
- datarooms: filteredDatarooms,
+ datarooms: dataroomsWithStats,
totalCount,
});
} catch (error) {