Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
error handler, helper function for api/documents/index
Aashish-Upadhyay-1013a1e9672a267
diff --git a/lib/errorHandler.ts b/lib/errorHandler.tsnew file mode 100644index 00000000..8cc1825b--- /dev/null+++ b/lib/errorHandler.ts@@ -0,0 +1,19 @@+import { NextApiResponse } from "next";++export class TeamError extends Error {+ statusCode = 400;+ constructor(public message: string) {+ super(message);+ }+}++export function errorHanlder(err: unknown, res: NextApiResponse) {+ if (err instanceof TeamError) {+ return res.status(err.statusCode).end(err.message);+ } else {+ return res.status(500).json({+ message: "Internal Server Error",+ error: (err as Error).message,+ });+ }+}diff --git a/lib/team/helper.ts b/lib/team/helper.tsnew file mode 100644index 00000000..346d2339--- /dev/null+++ b/lib/team/helper.ts@@ -0,0 +1,64 @@+import prisma from "@/lib/prisma";+import { TeamError } from "../errorHandler";++interface ITeamUserAndDocument {+ teamId: string;+ userId: string;+ docId?: string;+ ownerId?: string;+ options?: {};+}++export async function getTeamWithUsersAndDocument({+ teamId,+ userId,+ docId,+ ownerId,+ options,+}: ITeamUserAndDocument) {+ const team = await prisma.team.findUnique({+ where: {+ id: teamId,+ },+ include: {+ users: {+ select: {+ userId: true,+ },+ },+ documents: {+ ...options,+ },+ },+ });++ // check if the team exists+ if (!team) {+ throw new TeamError("Team doesn't exists");+ }++ // check if the user is part the team+ const teamHasUser = team?.users.some((user) => user.userId === userId);+ if (!teamHasUser) {+ throw new TeamError("You are not a member of the team");+ }++ // check if the document exists in the team+ let document: any;+ if (docId) {+ document = team?.documents.find((doc) => doc.id === docId);+ if (!document) {+ throw new TeamError("Document doesn't exists in the team");+ }+ }++ // Check that the user is owner of the document, otherwise return 401+ if (ownerId) {+ const isUserOwnerOfDocument = document.ownerId === userId;+ if (!isUserOwnerOfDocument) {+ throw new TeamError("Unauthorized access to the document");+ }+ }++ return { team, document };+}diff --git a/pages/api/teams/[teamId]/documents/index.ts b/pages/api/teams/[teamId]/documents/index.tsindex b6d3a646..f2b3ccdc 100644--- a/pages/api/teams/[teamId]/documents/index.ts+++ b/pages/api/teams/[teamId]/documents/index.ts@@ -5,6 +5,8 @@ import { authOptions } from "../../../auth/[...nextauth]";import { CustomUser } from "@/lib/types";import { getExtension, log } from "@/lib/utils";import { identifyUser, trackAnalytics } from "@/lib/analytics";+import { getTeamWithUsersAndDocument } from "@/lib/team/helper";+import { errorHanlder } from "@/lib/errorHandler";export default async function handle(req: NextApiRequest,@@ -22,60 +24,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 { team } = await getTeamWithUsersAndDocument({+ teamId,+ userId,+ options: {+ orderBy: {+ createdAt: "desc",},- documents: {- select: {- id: true,+ include: {+ _count: {+ select: { links: true, views: true, versions: true },+ },+ links: {+ take: 1,+ select: { id: 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");- }-- const documents = await prisma.document.findMany({- where: {- // ownerId: (session.user as CustomUser).id,- teamId: teamId,- },- orderBy: {- createdAt: "desc",- },- include: {- _count: {- select: { links: true, views: true, versions: true },- },- links: {- take: 1,- select: { id: true },- },- },- });+ const documents = team.documents;return res.status(200).json(documents);} catch (error) {- return res.status(500).json({- message: "Internal Server Error",- error: (error as Error).message,- });+ errorHanlder(error, res);}} else if (req.method === "POST") {// POST /api/teams/:teamId/documents@@ -90,35 +62,11 @@ 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,});- // 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");- }-// Assuming data is an object with `name` and `description` propertiesconst { name, url, numPages } = req.body;@@ -181,10 +129,7 @@ export default async function handle(return res.status(201).json(document);} 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 GET and POST requests