Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove pagination for the category endpoint #164

Merged
merged 1 commit into from
Sep 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 5 additions & 15 deletions src/controllers/category.controller.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,16 @@
import type { Request, Response } from 'express'
import type Category from '../entities/category.entity'
import { getAllCategories } from '../services/category.service'
import { type PaginatedApiResponse } from '../types'
import type { ApiResponse } from '../types'
import type Category from '../entities/category.entity'

export const getCategories = async (
req: Request,
res: Response
): Promise<Response<PaginatedApiResponse<Category>>> => {
): Promise<ApiResponse<Category>> => {
try {
const pageNumber = parseInt(req.query.pageNumber as string)
const pageSize = parseInt(req.query.pageSize as string)

const { statusCode, items, totalItemCount, message } =
await getAllCategories(pageNumber, pageSize)
const { statusCode, categories, message } = await getAllCategories()

return res.status(statusCode).json({
pageNumber,
pageSize,
totalItemCount,
items,
message
})
return res.status(statusCode).json({ categories, message })
} catch (err) {
if (err instanceof Error) {
console.error('Error executing query', err)
Expand Down
4 changes: 1 addition & 3 deletions src/routes/category/category.route.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
import express from 'express'
import { getCategories } from '../../controllers/category.controller'
import { requestQueryValidator } from '../../middlewares/requestValidator'
import { paginationSchema } from '../../schemas/common/pagination-request.schema'

const categoryRouter = express.Router()

categoryRouter.get('/', requestQueryValidator(paginationSchema), getCategories)
categoryRouter.get('/', getCategories)

export default categoryRouter
20 changes: 9 additions & 11 deletions src/services/category.service.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { getAllCategories } from './category.service'
import { dataSource } from '../configs/dbConfig'
import type Category from '../entities/category.entity'
import { getAllCategories } from './category.service'

jest.mock('../configs/dbConfig', () => ({
dataSource: {
Expand All @@ -22,37 +22,35 @@ describe('Category Service - getAllCategories', () => {
] as Category[]

const mockCategoryRepository = {
find: jest.fn().mockResolvedValue(mockCategories),
findAndCount: jest.fn().mockResolvedValue([mockCategories, 2])
find: jest.fn().mockResolvedValue(mockCategories)
}

;(dataSource.getRepository as jest.Mock).mockReturnValueOnce(
mockCategoryRepository
)

const result = await getAllCategories(1, 2)
const result = await getAllCategories()

expect(result.statusCode).toBe(200)
expect(result.items?.length).toBe(2)
expect(result.items).toEqual([
expect(result.categories?.length).toBe(2)
expect(result.categories).toEqual([
{ uuid: 'mock-uuid-1', category: 'Category 1' },
{ uuid: 'mock-uuid-2', category: 'Category 2' }
])
expect(result.message).toBe('Categories retrieved successfully')
expect(result.message).toBe('All Categories found')
})

it('should handle categories not found', async () => {
const mockCategoryRepository = {
find: jest.fn().mockResolvedValue([]),
findAndCount: jest.fn().mockResolvedValue([[], 0])
find: jest.fn().mockResolvedValue([])
}

;(dataSource.getRepository as jest.Mock).mockReturnValueOnce(
mockCategoryRepository
)

const result = await getAllCategories(1, 2)
const result = await getAllCategories()

expect(result.items?.length).toBe(0)
expect(result.categories?.length).toBe(0)
})
})
46 changes: 17 additions & 29 deletions src/services/category.service.ts
Original file line number Diff line number Diff line change
@@ -1,47 +1,35 @@
import { dataSource } from '../configs/dbConfig'
import Category from '../entities/category.entity'
import { type PaginatedApiResponse } from '../types'

export const getAllCategories = async (
pageNumber: number,
pageSize: number
): Promise<PaginatedApiResponse<Pick<Category, 'uuid' | 'category'>>> => {
export const getAllCategories = async (): Promise<{
statusCode: number
categories?: Array<Pick<Category, 'uuid' | 'category'>> | null
message: string
}> => {
try {
const categoryRepository = dataSource.getRepository(Category)
const allCategories: Category[] = await categoryRepository.find({
select: ['category', 'uuid']
})

const [allCategories, totalItemCount] =
await categoryRepository.findAndCount({
select: ['category', 'uuid'],
skip: (pageNumber - 1) * pageSize,
take: pageSize
})
const categories = allCategories.map((category) => {
return { category: category.category, uuid: category.uuid }
})

const items = allCategories.map((category) => ({
category: category.category,
uuid: category.uuid
}))

if (items.length === 0) {
if (!categories) {
return {
pageNumber,
pageSize,
totalItemCount,
items: [],
statusCode: 404,
message: 'No categories found'
message: 'Categories not found'
}
}

return {
pageNumber,
pageSize,
totalItemCount,
items,
statusCode: 200,
message: 'Categories retrieved successfully'
categories,
message: 'All Categories found'
}
} catch (err) {
console.error('Error getting categories', err)
throw new Error('Error getting categories')
console.error('Error getting mentor', err)
throw new Error('Error getting mentor')
}
}
Loading