Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
feat: improve queries
Marc Seitz6bb42dcde8a3
diff --git a/pages/api/teams/[teamId]/documents/[id]/links.ts b/pages/api/teams/[teamId]/documents/[id]/links.tsindex a27e99f3..fef4f77f 100644--- a/pages/api/teams/[teamId]/documents/[id]/links.ts+++ b/pages/api/teams/[teamId]/documents/[id]/links.ts@@ -22,11 +22,18 @@ export default async function handle(}const { teamId, id: docId } = req.query as { teamId: string; id: string };-const userId = (session.user as CustomUser).id;try {- // First check if document has any links to avoid expensive query+ // First, ensure the requester belongs to the team+ const teamHasUser = await prisma.team.findFirst({+ where: { id: teamId, users: { some: { userId } } },+ select: { id: true },+ });+ if (!teamHasUser) {+ return res.status(401).end("Unauthorized");+ }+ // Then check if document has any links to avoid expensive queryconst document = await prisma.document.findUnique({where: {id: docId,@@ -52,58 +59,36 @@ export default async function handle(return res.status(200).json([]);}- // Only fetch full link data if we have links- const { document: documentWithLinks } = await getTeamWithUsersAndDocument(- {- teamId,- userId,- docId,- checkOwner: true,- options: {- select: {- ownerId: true,- id: true,- links: {- where: { isArchived: false },- orderBy: {- createdAt: "desc",- },- include: {- views: {- orderBy: {- viewedAt: "desc",- },- },- feedback: {- select: {- id: true,- data: true,- },- },- customFields: {- select: {- orderIndex: true,- label: true,- identifier: true,- placeholder: true,- type: true,- required: true,- },- orderBy: {- orderIndex: "asc",- },- },- _count: {- select: { views: true },- },+ // Only fetch full link data if we have links (target only this document)+ const docWithLinks = await prisma.document.findUnique({+ where: { id: docId, teamId },+ select: {+ id: true,+ ownerId: true,+ links: {+ where: { isArchived: false },+ orderBy: { createdAt: "desc" },+ include: {+ views: { orderBy: { viewedAt: "desc" } },+ feedback: { select: { id: true, data: true } },+ customFields: {+ select: {+ orderIndex: true,+ label: true,+ identifier: true,+ placeholder: true,+ type: true,+ required: true,},+ orderBy: { orderIndex: "asc" },},+ _count: { select: { views: true } },},},},- );+ });- let links = documentWithLinks!.links;+ let links = docWithLinks!.links;// Decrypt the password for each linkif (links && links.length > 0) {diff --git a/pages/api/teams/[teamId]/documents/[id]/overview.ts b/pages/api/teams/[teamId]/documents/[id]/overview.tsindex 99ff7c90..faac3dfe 100644--- a/pages/api/teams/[teamId]/documents/[id]/overview.ts+++ b/pages/api/teams/[teamId]/documents/[id]/overview.ts@@ -2,6 +2,7 @@ import { NextApiRequest, NextApiResponse } from "next";import { getLimits } from "@/ee/limits/server";import { authOptions } from "@/pages/api/auth/[...nextauth]";+import { Prisma } from "@prisma/client";import { getServerSession } from "next-auth/next";import { getFeatureFlags } from "@/lib/featureFlags";@@ -9,33 +10,7 @@ import prisma from "@/lib/prisma";import { usePlan } from "@/lib/swr/use-billing";import { getTeamWithUsersAndDocument } from "@/lib/team/helper";import { CustomUser } from "@/lib/types";--// Helper function to serialize BigInt values to strings-function serializeBigInt(obj: any): any {- if (obj === null || obj === undefined) {- return obj;- }-- if (typeof obj === "bigint") {- return obj.toString();- }-- if (Array.isArray(obj)) {- return obj.map(serializeBigInt);- }-- if (typeof obj === "object") {- const serialized: any = {};- for (const key in obj) {- if (obj.hasOwnProperty(key)) {- serialized[key] = serializeBigInt(obj[key]);- }- }- return serialized;- }-- return obj;-}+import { serializeFileSize } from "@/lib/utils";export default async function handle(req: NextApiRequest,@@ -161,7 +136,7 @@ export default async function handle(where: {versionId: primaryVersion.id,pageLinks: {- not: "null" as any,+ not: Prisma.JsonNull,},},});@@ -171,17 +146,17 @@ export default async function handle(// Basic response for instant loadingconst response = {document: {- ...serializeBigInt(document),- primaryVersion: serializeBigInt(primaryVersion),+ ...serializeFileSize(document),+ primaryVersion: serializeFileSize(primaryVersion),hasPageLinks,isEmpty: !hasLinks && !hasViews, // Flag for empty state optimization},limits: {- canAddLinks: limits?.links- ? document._count.links < limits.links+ canAddLinks: limits?.links ? limits?.usage?.links < limits.links : true,+ canAddDocuments: limits?.documents+ ? limits?.usage?.documents < limits.documents: true,- canAddDocuments: limits?.documents ? true : true, // Simplified for this context- canAddUsers: limits?.users ? true : true,+ canAddUsers: limits?.users ? limits?.usage?.users < limits.users : true,},featureFlags: {annotations: featureFlags.annotations,diff --git a/pages/api/teams/[teamId]/documents/[id]/stats.ts b/pages/api/teams/[teamId]/documents/[id]/stats.tsindex 7598be92..69ab3068 100644--- a/pages/api/teams/[teamId]/documents/[id]/stats.ts+++ b/pages/api/teams/[teamId]/documents/[id]/stats.ts@@ -36,6 +36,14 @@ export default async function handle(const userId = (session.user as CustomUser).id;try {+ const teamHasUser = await prisma.team.findUnique({+ where: { id: teamId, users: { some: { userId } } },+ });++ if (!teamHasUser) {+ return res.status(401).end("Unauthorized");+ }+// First check if document exists and get basic infoconst document = await prisma.document.findUnique({where: {@@ -45,11 +53,6 @@ export default async function handle(select: {id: true,teamId: true,- team: {- select: {- plan: true,- },- },_count: {select: {views: { where: { isArchived: false } },diff --git a/pages/documents/[id]/index.tsx b/pages/documents/[id]/index.tsxindex d3809de1..2b74ddc8 100644--- a/pages/documents/[id]/index.tsx+++ b/pages/documents/[id]/index.tsx@@ -81,6 +81,7 @@ export default function DocumentPage() {// Always fetch links to show empty states properlyconst { links, error: linksError, mutate: mutateLinks } = useDocumentLinks();const teamInfo = useTeam();+ const teamId = teamInfo?.currentTeam?.id;const [isLinkSheetOpen, setIsLinkSheetOpen] = useState<boolean>(false);@@ -131,7 +132,7 @@ export default function DocumentPage() {);}- if (!prismaDocument || !primaryVersion) {+ if (!prismaDocument || !primaryVersion || !teamId) {return (<AppLayout><main className="relative mx-2 mb-10 mt-4 space-y-8 overflow-hidden px-1 sm:mx-3 md:mx-5 md:mt-5 lg:mx-7 lg:mt-8 xl:mx-10">@@ -150,7 +151,7 @@ export default function DocumentPage() {<DocumentHeaderprimaryVersion={primaryVersion}prismaDocument={prismaDocument}- teamId={teamInfo?.currentTeam?.id!}+ teamId={teamId}actions={[<NotionAccessibilityIndicatorkey={"notion-status"}@@ -162,7 +163,7 @@ export default function DocumentPage() {{featureFlags?.annotations && (<AnnotationSheetdocumentId={prismaDocument.id}- teamId={teamInfo?.currentTeam?.id!}+ teamId={teamId}numPages={primaryVersion.numPages || 1}/>)}@@ -212,7 +213,7 @@ export default function DocumentPage() {<VideoAnalyticsdocumentId={prismaDocument.id}primaryVersion={primaryVersion}- teamId={teamInfo?.currentTeam?.id!}+ teamId={teamId}/>))}