The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Speed up GET /api/tags with includeLinksCount (#3731)
Pedro Ladeira332b85b08a82
diff --git a/apps/web/app/api/tags/route.ts b/apps/web/app/api/tags/route.tsindex 9aa8bf72e4..088e6ef731 100644--- a/apps/web/app/api/tags/route.ts+++ b/apps/web/app/api/tags/route.ts@@ -24,38 +24,67 @@ export const GET = withWorkspace(includeLinksCount,} = getTagsQuerySchemaExtended.parse(searchParams);- const tags = await prisma.tag.findMany({- where: {- projectId: workspace.id,- ...(search && {- name: {- contains: search,- },- }),- ...(ids && {- id: {- in: ids,- },- }),- },+ const tagWhere = {+ projectId: workspace.id,+ ...(search && {+ name: {+ contains: search,+ },+ }),+ ...(ids && {+ id: {+ in: ids,+ },+ }),+ };++ const listArgs = {+ where: tagWhere,select: {id: true,name: true,color: true,- ...(includeLinksCount && {- _count: {- select: {- links: true,- },- },- }),},orderBy: {[sortBy]: sortOrder,},take: pageSize,skip: (page - 1) * pageSize,- });+ };++ let tags;++ if (includeLinksCount) {+ const rows = await prisma.tag.findMany(listArgs);+ const tagIds = rows.map((t) => t.id);++ if (tagIds.length === 0) {+ tags = [];+ } else {+ const countsByTag = await prisma.linkTag.groupBy({+ by: ["tagId"],+ where: {+ tagId: { in: tagIds },+ },+ _count: {+ _all: true,+ },+ });++ const countMap = new Map(+ countsByTag.map((c) => [c.tagId, c._count._all]),+ );++ tags = rows.map((row) => ({+ ...row,+ _count: {+ links: countMap.get(row.id) ?? 0,+ },+ }));+ }+ } else {+ tags = await prisma.tag.findMany(listArgs);+ }return NextResponse.json(tags, { headers });},