Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
document api with team helper
Aashish-Upadhyay-101d9aaea359b0c
diff --git a/lib/team/helper.ts b/lib/team/helper.tsindex 346d2339..abf46294 100644--- a/lib/team/helper.ts+++ b/lib/team/helper.ts@@ -5,7 +5,7 @@ interface ITeamUserAndDocument {teamId: string;userId: string;docId?: string;- ownerId?: string;+ checkOwner?: boolean; // will be deprecated in the futureoptions?: {};}@@ -13,7 +13,7 @@ export async function getTeamWithUsersAndDocument({teamId,userId,docId,- ownerId,+ checkOwner,options,}: ITeamUserAndDocument) {const team = await prisma.team.findUnique({@@ -53,7 +53,7 @@ export async function getTeamWithUsersAndDocument({}// Check that the user is owner of the document, otherwise return 401- if (ownerId) {+ if (checkOwner) {const isUserOwnerOfDocument = document.ownerId === userId;if (!isUserOwnerOfDocument) {throw new TeamError("Unauthorized access to the document");diff --git a/pages/api/teams/[teamId]/documents/[id]/index.ts b/pages/api/teams/[teamId]/documents/[id]/index.tsindex bdb6d37e..7daeb176 100644--- a/pages/api/teams/[teamId]/documents/[id]/index.ts+++ b/pages/api/teams/[teamId]/documents/[id]/index.ts@@ -4,6 +4,8 @@ import prisma from "@/lib/prisma";import { authOptions } from "../../../../auth/[...nextauth]";import { CustomUser } from "@/lib/types";import { del } from "@vercel/blob";+import { getTeamWithUsersAndDocument } from "@/lib/team/helper";+import { errorHanlder } from "@/lib/errorHandler";export default async function handle(req: NextApiRequest,@@ -21,46 +23,22 @@ export default async function handle(const userId = (session.user as CustomUser).id;try {- const team = await prisma.team.findUnique({- where: {- id: teamId,- },- include: {- users: {- select: {- userId: true,- },- },- documents: {- include: {- // Get the latest primary version of the document- versions: {- where: { isPrimary: true },- orderBy: { createdAt: "desc" },- take: 1,- },+ const { document } = await getTeamWithUsersAndDocument({+ teamId,+ userId,+ docId,+ options: {+ include: {+ // Get the latest primary version of the document+ versions: {+ where: { isPrimary: true },+ orderBy: { createdAt: "desc" },+ take: 1,},},},});- // check if the team exists- if (!team) {- return res.status(400).end("Team doesn't exists");- }-- // check if the user is part the team- const teamHasUser = team?.users.some((user) => user.userId === userId);- if (!teamHasUser) {- return res.status(401).end("You are not a member of the team");- }-- // check if the document exists in the team- const document = team?.documents.find((doc) => doc.id === docId);- if (!document) {- return res.status(400).end("Document doesn't exists in the team");- }-// Check that the user is owner of the document, otherwise return 401// if (document.ownerId !== (session.user as CustomUser).id) {// return res.status(401).end("Unauthorized to access this document");@@ -68,10 +46,7 @@ export default async function handle(return res.status(200).json(document);} catch (error) {- return res.status(500).json({- message: "Internal Server Error",- error: (error as Error).message,- });+ errorHanlder(error, res);}} else if (req.method === "DELETE") {// DELETE /api/teams/:teamId/document/:id@@ -86,48 +61,20 @@ export default async function handle(const userId = (session.user as CustomUser).id;try {- const team = await prisma.team.findUnique({- where: {- id: teamId,- },- include: {- users: {- select: {- userId: true,- },- },- documents: {- select: {- id: true,- ownerId: true,- file: true,- },+ const { document } = await getTeamWithUsersAndDocument({+ teamId,+ userId,+ docId,+ checkOwner: true,+ options: {+ select: {+ id: true,+ ownerId: true,+ file: true,},},});- // check if the team exists- if (!team) {- return res.status(400).end("Team doesn't exists");- }-- // check if the user is part the team- const teamHasUser = team?.users.some((user) => user.userId === userId);- if (!teamHasUser) {- return res.status(401).end("You are not a member of the team");- }-- // check if the document exists in the team- const document = team?.documents.find((doc) => doc.id === docId);- if (!document) {- return res.status(400).end("Document doesn't exists in the team");- }-- // check that the user is owner of the document, otherwise return 401- if (document.ownerId !== userId) {- return res.status(401).end("Unauthorized to access the document");- }-// delete the document from vercel blobawait del(document.file);// delete the document from database@@ -139,10 +86,7 @@ export default async function handle(return res.status(204).end(); // 204 No Content response for successful deletes} catch (error) {- return res.status(500).json({- message: "Internal Server Error",- error: (error as Error).message,- });+ errorHanlder(error, res);}} else {// We only allow GET and DELETE requestsdiff --git a/pages/api/teams/[teamId]/documents/[id]/links.ts b/pages/api/teams/[teamId]/documents/[id]/links.tsindex b906f66c..d6883fb3 100644--- a/pages/api/teams/[teamId]/documents/[id]/links.ts+++ b/pages/api/teams/[teamId]/documents/[id]/links.ts@@ -4,6 +4,8 @@ import prisma from "@/lib/prisma";import { authOptions } from "../../../../auth/[...nextauth]";import { log } from "@/lib/utils";import { CustomUser } from "@/lib/types";+import { getTeamWithUsersAndDocument } from "@/lib/team/helper";+import { errorHanlder } from "@/lib/errorHandler";export default async function handle(req: NextApiRequest,@@ -21,71 +23,39 @@ export default async function handle(const userId = (session.user as CustomUser).id;try {- const team = await prisma.team.findUnique({- where: {- id: teamId,- },- include: {- users: {- select: {- userId: true,- },- },- documents: {- select: {- ownerId: true,- id: true,- links: {- orderBy: {- createdAt: "asc",- },- include: {- views: {- orderBy: {- viewedAt: "desc",- },- },- _count: {- select: { views: true },+ const { document } = await getTeamWithUsersAndDocument({+ teamId,+ userId,+ docId,+ checkOwner: true,+ options: {+ select: {+ ownerId: true,+ id: true,+ links: {+ orderBy: {+ createdAt: "asc",+ },+ include: {+ views: {+ orderBy: {+ viewedAt: "desc",},},+ _count: {+ select: { views: true },+ },},},},},});- // check if the team exists- if (!team) {- return res.status(400).end("Team doesn't exists");- }-- // check if the user is part the team- const teamHasUser = team?.users.some((user) => user.userId === userId);- if (!teamHasUser) {- return res.status(401).end("You are not a member of the team");- }-- // check if the document exists in the team- const document = team?.documents.find((doc) => doc.id === docId);- if (!document) {- return res.status(400).end("Document doesn't exists in the team");- }-- // Check that the user is owner of the document, otherwise return 401- const isUserOwnerOfDocument = document.ownerId === userId;- if (!isUserOwnerOfDocument) {- return res.status(401).end("Unauthorized access to the document");- }-const links = document.links;return res.status(200).json(links);} catch (error) {log(`Failed to get links for document ${docId}. Error: \n\n ${error}`);- return res.status(500).json({- message: "Internal Server Error",- error: (error as Error).message,- });+ errorHanlder(error, res);}} else {// We only allow GET requestsdiff --git a/pages/api/teams/[teamId]/documents/[id]/stats.ts b/pages/api/teams/[teamId]/documents/[id]/stats.tsindex 913a1a93..f62452a9 100644--- a/pages/api/teams/[teamId]/documents/[id]/stats.ts+++ b/pages/api/teams/[teamId]/documents/[id]/stats.ts@@ -4,6 +4,8 @@ import prisma from "@/lib/prisma";import { authOptions } from "../../../../auth/[...nextauth]";import { getTotalAvgPageDuration } from "@/lib/tinybird";import { CustomUser } from "@/lib/types";+import { getTeamWithUsersAndDocument } from "@/lib/team/helper";+import { errorHanlder } from "@/lib/errorHandler";export default async function handle(req: NextApiRequest,@@ -21,49 +23,18 @@ export default async function handle(const userId = (session.user as CustomUser).id;try {- const team = await prisma.team.findUnique({- where: {- id: teamId,- },- include: {- users: {- select: {- userId: true,- },- },- documents: {- select: {- ownerId: true,- id: true,- views: true,- },+ const { document } = await getTeamWithUsersAndDocument({+ teamId,+ userId,+ docId,+ checkOwner: true,+ options: {+ include: {+ views: true,},},});- // check if the team exists- if (!team) {- return res.status(400).end("Team doesn't exists");- }-- // check if the user is part the team- const teamHasUser = team?.users.some((user) => user.userId === userId);- if (!teamHasUser) {- return res.status(401).end("You are not a member of the team");- }-- // check if the document exists in the team- const document = team?.documents.find((doc) => doc.id === docId);- if (!document) {- return res.status(400).end("Document doesn't exists in the team");- }-- // Check that the user is owner of the document, otherwise return 401- const isUserOwnerOfDocument = document.ownerId === userId;- if (!isUserOwnerOfDocument) {- return res.status(401).end("Unauthorized access to the document");- }-const views = document.views;const groupedViews = await prisma.view.groupBy({@@ -86,10 +57,7 @@ export default async function handle(return res.status(200).json(stats);} catch (error) {- return res.status(500).json({- message: "Internal Server Error",- error: (error as Error).message,- });+ errorHanlder(error, res);}} else {// We only allow GET requestsdiff --git a/pages/api/teams/[teamId]/documents/[id]/views/[viewId]/stats.ts b/pages/api/teams/[teamId]/documents/[id]/views/[viewId]/stats.tsindex 0840aaf9..4d2ec18d 100644--- a/pages/api/teams/[teamId]/documents/[id]/views/[viewId]/stats.ts+++ b/pages/api/teams/[teamId]/documents/[id]/views/[viewId]/stats.ts@@ -4,6 +4,8 @@ import { getViewPageDuration } from "@/lib/tinybird";import { authOptions } from "@/pages/api/auth/[...nextauth]";import { CustomUser } from "@/lib/types";import prisma from "@/lib/prisma";+import { getTeamWithUsersAndDocument } from "@/lib/team/helper";+import { errorHanlder } from "@/lib/errorHandler";export default async function handle(req: NextApiRequest,@@ -29,48 +31,19 @@ export default async function handle(const userId = (session.user as CustomUser).id;try {- const team = await prisma.team.findUnique({- where: {- id: teamId,- },- include: {- users: {- select: {- userId: true,- },- },- documents: {- select: {- id: true,- ownerId: true,- },+ await getTeamWithUsersAndDocument({+ teamId,+ userId,+ docId,+ checkOwner: true,+ options: {+ select: {+ id: true,+ ownerId: true,},},});- // check if the team exists- if (!team) {- return res.status(400).end("Team doesn't exists");- }-- // check if the user is part the team- const teamHasUser = team?.users.some((user) => user.userId === userId);- if (!teamHasUser) {- return res.status(401).end("You are not a member of the team");- }-- // check if the document exists in the team- const document = team?.documents.find((doc) => doc.id === docId);- if (!document) {- return res.status(400).end("Document doesn't exists in the team");- }-- // Check that the user is owner of the document, otherwise return 401- const isUserOwnerOfDocument = document.ownerId === userId;- if (!isUserOwnerOfDocument) {- return res.status(401).end("Unauthorized access to the document");- }-const duration = await getViewPageDuration({documentId: docId,viewId: viewId,@@ -86,10 +59,7 @@ export default async function handle(return res.status(200).json(stats);} catch (error) {- return res.status(500).json({- message: "Internal Server Error",- error: (error as Error).message,- });+ errorHanlder(error, res);}} else {// We only allow GET and POST requestsdiff --git a/pages/api/teams/[teamId]/documents/[id]/views/index.ts b/pages/api/teams/[teamId]/documents/[id]/views/index.tsindex 67f5e43e..c085ef5e 100644--- a/pages/api/teams/[teamId]/documents/[id]/views/index.ts+++ b/pages/api/teams/[teamId]/documents/[id]/views/index.ts@@ -5,6 +5,8 @@ import { log } from "@/lib/utils";import { getViewPageDuration } from "@/lib/tinybird";import { authOptions } from "@/pages/api/auth/[...nextauth]";import { CustomUser } from "@/lib/types";+import { getTeamWithUsersAndDocument } from "@/lib/team/helper";+import { errorHanlder } from "@/lib/errorHandler";export default async function handle(req: NextApiRequest,@@ -24,36 +26,30 @@ export default async function handle(const userId = (session.user as CustomUser).id;try {- const team = await prisma.team.findUnique({- where: {- id: teamId,- },- include: {- users: {- select: {- userId: true,+ const { document } = await getTeamWithUsersAndDocument({+ teamId,+ userId,+ docId,+ checkOwner: true,+ options: {+ select: {+ id: true,+ ownerId: true,+ numPages: true,+ versions: {+ where: { isPrimary: true },+ orderBy: { createdAt: "desc" },+ take: 1,+ select: { numPages: true },},- },- documents: {- select: {- id: true,- ownerId: true,- numPages: true,- versions: {- where: { isPrimary: true },- orderBy: { createdAt: "desc" },- take: 1,- select: { numPages: true },+ views: {+ orderBy: {+ viewedAt: "desc",},- views: {- orderBy: {- viewedAt: "desc",- },- include: {- link: {- select: {- name: true,- },+ include: {+ link: {+ select: {+ name: true,},},},@@ -62,36 +58,13 @@ export default async function handle(},});- // check if the team exists- if (!team) {- return res.status(400).end("Team doesn't exists");- }-- // check if the user is part the team- const teamHasUser = team?.users.some((user) => user.userId === userId);- if (!teamHasUser) {- return res.status(401).end("You are not a member of the team");- }-- // check if the document exists in the team- const document = team?.documents.find((doc) => doc.id === docId);- if (!document) {- return res.status(400).end("Document doesn't exists in the team");- }-- // Check that the user is owner of the document, otherwise return 401- const isUserOwnerOfDocument = document.ownerId === userId;- if (!isUserOwnerOfDocument) {- return res.status(401).end("Unauthorized access to the document");- }-// get the numPages from documentconst numPages =document?.versions[0]?.numPages || document?.numPages || 0;const views = document.views;- const durationsPromises = views.map((view) => {+ const durationsPromises = views.map((view: { id: string }) => {return getViewPageDuration({documentId: docId,viewId: view.id,@@ -104,13 +77,14 @@ export default async function handle(// Sum up durations for each viewconst summedDurations = durations.map((duration) => {return duration.data.reduce(- (totalDuration, data) => totalDuration + data.sum_duration,+ (totalDuration: number, data: { sum_duration: number }) =>+ totalDuration + data.sum_duration,0);});// Construct the response combining views and their respective durations- const viewsWithDuration = views.map((view, index) => {+ const viewsWithDuration = views.map((view: any, index: number) => {// calculate the completion rateconst completionRate = numPages? (durations[index].data.length / numPages) * 100@@ -129,10 +103,7 @@ export default async function handle(return res.status(200).json(viewsWithDuration);} catch (error) {log(`Failed to get views for link ${docId}. Error: \n\n ${error}`);- return res.status(500).json({- message: "Internal Server Error",- error: (error as Error).message,- });+ errorHanlder(error, res);}} else {// We only allow GET requestsdiff --git a/pages/api/teams/[teamId]/documents/update.ts b/pages/api/teams/[teamId]/documents/update.tsindex 3a9229de..829a16d8 100644--- a/pages/api/teams/[teamId]/documents/update.ts+++ b/pages/api/teams/[teamId]/documents/update.ts@@ -4,6 +4,8 @@ import prisma from "@/lib/prisma";import { authOptions } from "../../../auth/[...nextauth]";import { CustomUser } from "@/lib/types";import { getExtension, log } from "@/lib/utils";+import { getTeamWithUsersAndDocument } from "@/lib/team/helper";+import { errorHanlder } from "@/lib/errorHandler";export default async function handle(req: NextApiRequest,@@ -25,43 +27,12 @@ export default async function handle(const userId = (session.user as CustomUser).id;try {- const team = await prisma.team.findUnique({- where: {- id: teamId,- },- include: {- users: {- select: {- userId: true,- },- },- documents: {- select: {- id: true,- },- },- },+ await getTeamWithUsersAndDocument({+ teamId,+ userId,+ docId: documentId,});- // check if the team exists- if (!team) {- return res.status(400).end("Team doesn't exists");- }-- // check if the user is part the team- const teamHasUser = team?.users.some((user) => user.userId === userId);- if (!teamHasUser) {- return res.status(401).end("You are not a member of the team");- }-- // check if the document exists in the team- const teamHasDocument = team?.documents.some(- (doc) => doc.id === documentId- );- if (!teamHasDocument) {- return res.status(400).end("Document doesn't exists in the team");- }-// Save data to the databaseawait prisma.document.update({where: { id: documentId },@@ -79,10 +50,7 @@ export default async function handle(return res.status(201).json({ message: "Document updated successfully" });} catch (error) {log(`Failed to create document. Error: \n\n ${error}`);- res.status(500).json({- message: "Internal Server Error",- error: (error as Error).message,- });+ errorHanlder(error, res);}} else {// We only allow POST requests