Skip to content

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

fix: n+1 link query

Marc Seitz3188db999ae7
diff --git a/pages/api/teams/[teamId]/documents/[id]/links.ts b/pages/api/teams/[teamId]/documents/[id]/links.ts
index 7d4659d6..77cb7a13 100644
--- a/pages/api/teams/[teamId]/documents/[id]/links.ts
+++ b/pages/api/teams/[teamId]/documents/[id]/links.ts
@@ -58,6 +58,7 @@ export default async function handle(
}
// Only fetch full link data if we have links (target only this document)
+ // Optimized: Only fetch the most recent view per link instead of all views
const docWithLinks = await prisma.document.findUnique({
where: { id: docId, teamId },
select: {
@@ -67,7 +68,11 @@ export default async function handle(
where: { deletedAt: null }, // exclude deleted links
orderBy: { createdAt: "desc" },
include: {
- views: { orderBy: { viewedAt: "desc" } },
+ // Only fetch the most recent view (needed for "last viewed" display)
+ views: {
+ orderBy: { viewedAt: "desc" },
+ take: 1,
+ },
feedback: { select: { id: true, data: true } },
customFields: {
select: {
@@ -86,42 +91,65 @@ export default async function handle(
},
});
- let links = docWithLinks!.links;
+ const links = docWithLinks!.links;
- // Decrypt the password for each link
- if (links && links.length > 0) {
- links = await Promise.all(
- links.map(async (link) => {
- // Decrypt the password if it exists
- if (link.password !== null) {
- link.password = decryptEncrpytedPassword(link.password);
- }
- const tags = await prisma.tag.findMany({
- where: {
- items: {
- some: {
- linkId: link.id,
- itemType: "LINK_TAG",
- },
- },
- },
- select: {
- id: true,
- name: true,
- color: true,
- description: true,
- },
- });
-
- return {
- ...link,
- tags,
- };
- }),
- );
+ // Early return if no links found
+ if (!links || links.length === 0) {
+ return res.status(200).json([]);
}
- return res.status(200).json(links);
+ // Collect all link IDs for batch tag query
+ const linkIds = links.map((link) => link.id);
+
+ // Batch fetch all tags for all links in a single query (fixes N+1 problem)
+ const tagItems = await prisma.tagItem.findMany({
+ where: {
+ linkId: { in: linkIds },
+ itemType: "LINK_TAG",
+ },
+ select: {
+ linkId: true,
+ tag: {
+ select: {
+ id: true,
+ name: true,
+ color: true,
+ description: true,
+ },
+ },
+ },
+ });
+
+ // Group tags by linkId for O(1) lookup
+ const tagsByLinkId = tagItems.reduce(
+ (acc, item) => {
+ if (item.linkId) {
+ if (!acc[item.linkId]) {
+ acc[item.linkId] = [];
+ }
+ acc[item.linkId].push(item.tag);
+ }
+ return acc;
+ },
+ {} as Record<string, (typeof tagItems)[0]["tag"][]>,
+ );
+
+ // Map links with decrypted passwords and tags
+ const linksWithTags = links.map((link) => {
+ // Decrypt the password if it exists
+ const decryptedPassword =
+ link.password !== null
+ ? decryptEncrpytedPassword(link.password)
+ : null;
+
+ return {
+ ...link,
+ password: decryptedPassword,
+ tags: tagsByLinkId[link.id] || [],
+ };
+ });
+
+ return res.status(200).json(linksWithTags);
} catch (error) {
log({
message: `Failed to get links for document: _${docId}_. \n\n ${error} \n\n*Metadata*: \`{teamId: ${teamId}, userId: ${userId}}\``,