From 3760d23abc4d02eb2c3823b8aa322f53914fd9b6 Mon Sep 17 00:00:00 2001 From: Mohamed Bassem Date: Sat, 6 Sep 2025 06:24:05 +0000 Subject: refactor: Extract quota logic into its own class --- packages/trpc/routers/bookmarks.ts | 33 ++++++++++++--------------------- 1 file changed, 12 insertions(+), 21 deletions(-) (limited to 'packages/trpc/routers') diff --git a/packages/trpc/routers/bookmarks.ts b/packages/trpc/routers/bookmarks.ts index 298f0961..db9d33fc 100644 --- a/packages/trpc/routers/bookmarks.ts +++ b/packages/trpc/routers/bookmarks.ts @@ -1,5 +1,5 @@ import { experimental_trpcMiddleware, TRPCError } from "@trpc/server"; -import { and, count, eq, gt, inArray, lt, or } from "drizzle-orm"; +import { and, eq, gt, inArray, lt, or } from "drizzle-orm"; import { EnqueueOptions } from "liteque"; import invariant from "tiny-invariant"; import { z } from "zod"; @@ -20,8 +20,8 @@ import { bookmarkTexts, customPrompts, tagsOnBookmarks, - users, } from "@karakeep/db/schema"; +import { QuotaService } from "@karakeep/shared-server"; import { deleteAsset, SUPPORTED_BOOKMARK_ASSET_TYPES, @@ -273,26 +273,17 @@ export const bookmarksAppRouter = router({ } // Check user quota - const user = await ctx.db.query.users.findFirst({ - where: eq(users.id, ctx.user.id), - columns: { - bookmarkQuota: true, - }, - }); - - if (user?.bookmarkQuota !== null && user?.bookmarkQuota !== undefined) { - const currentBookmarkCount = await ctx.db - .select({ count: count() }) - .from(bookmarks) - .where(eq(bookmarks.userId, ctx.user.id)); - - if (currentBookmarkCount[0].count >= user.bookmarkQuota) { - throw new TRPCError({ - code: "FORBIDDEN", - message: `Bookmark quota exceeded. You can only have ${user.bookmarkQuota} bookmarks.`, - }); - } + const quotaResult = await QuotaService.canCreateBookmark( + ctx.db, + ctx.user.id, + ); + if (!quotaResult.result) { + throw new TRPCError({ + code: "FORBIDDEN", + message: quotaResult.error, + }); } + const bookmark = await ctx.db.transaction(async (tx) => { const bookmark = ( await tx -- cgit v1.2.3-70-g09d2