Skip to content

Commit

Permalink
Merge pull request #39 from Iknow6aint/main
Browse files Browse the repository at this point in the history
Modify getCampaignsByCategory to Use Cursor-Based Pagination isssue #33
  • Loading branch information
EjembiEmmanuel authored Feb 28, 2025
2 parents 4ff9032 + 6540aa6 commit 40a2e59
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 3 deletions.
29 changes: 26 additions & 3 deletions src/resolvers/campaign.resolver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { Resolver, Query, Args, Mutation, Int } from '@nestjs/graphql';
import { PrismaService } from 'src/prisma/prisma.service';
import { Campaign } from './models/campaign.model';
import { CampaignCreateInput } from './dtos/createCampaign.dto';
import { PaginatedCampaigns, PaginationInput } from './dtos/pagination.models';
import { CampaignConnection } from './dtos/getCampaigns.dto';

@Resolver(() => Campaign)
Expand Down Expand Up @@ -93,16 +94,38 @@ export class CampaignResolver {
return campaign;
}

@Query(() => [Campaign])
async getCampaignByCategory(@Args('name') name: string): Promise<Campaign[]> {
@Query(() => PaginatedCampaigns)
async getCampaignsByCategory(
@Args('name') name: string,
@Args('pagination', { nullable: true }) pagination?: PaginationInput,
): Promise<PaginatedCampaigns> {
try {
return await this.prismaService.campaign.findMany({
const { cursor, limit, skip } = pagination || {};

// Fetch campaigns with pagination
const campaigns = await this.prismaService.campaign.findMany({
where: { category: { name } },
include: { campaign_images: true, category: true },
orderBy: {
created_at: 'desc',
},
take: limit,
skip: skip,
cursor: cursor ? { campaign_id: cursor } : undefined,
});

const totalCount = await this.prismaService.campaign.count({
where: { category: { name } },
});

// Determine if there is a next page
const hasNextPage = campaigns.length === limit;

return {
campaigns,
totalCount,
hasNextPage,
};
} catch (error) {
this.logger.error(
'Failed to retrieve campaigns by category',
Expand Down
26 changes: 26 additions & 0 deletions src/resolvers/dtos/pagination.models.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { Field, InputType, Int, ObjectType } from '@nestjs/graphql';
import { Campaign } from '../models/campaign.model';

@ObjectType()
export class PaginatedCampaigns {
@Field(() => [Campaign])
campaigns: Campaign[];

@Field(() => Int)
totalCount: number;

@Field(() => Boolean)
hasNextPage: boolean;
}

@InputType()
export class PaginationInput {
@Field(() => Int, { nullable: true })
cursor?: number;

@Field(() => Int)
limit: number;

@Field(() => Int, { nullable: true })
skip?: number;
}

0 comments on commit 40a2e59

Please sign in to comment.