Skip to content

Commit

Permalink
Optimize for use-case of only thread count
Browse files Browse the repository at this point in the history
This is pre-mature optimization but it's a query that
is called on every page load for our main detail pages.
That's a hot path, so I'm taking the effort here.
  • Loading branch information
CarsonF committed Oct 10, 2024
1 parent be52e1a commit 3b3c0dd
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 2 deletions.
14 changes: 14 additions & 0 deletions src/components/comments/comment-thread.repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,4 +98,18 @@ export class CommentThreadRepository extends DtoRepository(CommentThread) {
.first();
return result!; // result from paginate() will always have 1 row.
}

async count(parent: ID) {
const result = await this.db
.query()
.match([
node('node', 'CommentThread'),
relation('in', '', 'commentThread', ACTIVE),
node('', 'BaseNode', { id: parent }),
])
.return<{ count: number }>('count(node) as count')
.map('count')
.first();
return result!;
}
}
12 changes: 12 additions & 0 deletions src/components/comments/comment.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,18 @@ export class CommentService {
}
}

async getThreadCount(parent: Commentable, session: Session) {
const perms = await this.getPermissionsFromResource(parent, session);

// Do check here since we don't filter in the db query.
// Will need to be updated with DB switch.
if (!perms.can('read')) {
return 0;
}

return await this.repo.threads.count(parent.id);
}

async listThreads(
parent: Commentable,
input: CommentThreadListInput,
Expand Down
11 changes: 9 additions & 2 deletions src/components/comments/commentable.resolver.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import { Parent, Query, ResolveField, Resolver } from '@nestjs/graphql';
import { Info, Parent, Query, ResolveField, Resolver } from '@nestjs/graphql';
import {
Fields,
ID,
IdArg,
IsOnly,
ListArg,
LoggedInSession,
Resource,
Expand Down Expand Up @@ -31,7 +33,12 @@ export class CommentableResolver {
@ListArg(CommentThreadListInput) input: CommentThreadListInput,
@LoggedInSession() session: Session,
@Loader(CommentThreadLoader) commentThreads: LoaderOf<CommentThreadLoader>,
): Promise<CommentThreadList> {
@Info(Fields, IsOnly(['total'])) onlyTotal: boolean,
) {
if (onlyTotal) {
const total = await this.service.getThreadCount(parent, session);
return { total };
}
const list = await this.service.listThreads(parent, input, session);
commentThreads.primeAll(list.items);
return list;
Expand Down

0 comments on commit 3b3c0dd

Please sign in to comment.