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

feat(api): Add pagination metadata to Environment module #382

Merged
merged 9 commits into from
Jul 29, 2024
93 changes: 93 additions & 0 deletions apps/api/src/common/paginate.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import { paginate } from './paginate'

describe('paginate', () => {
it('should paginate without default query', () => {
const totalCount = 100
const relativeUrl = '/items'
const query = { page: 2, limit: 10 }

const result = paginate(totalCount, relativeUrl, query)

expect(result).toBeDefined()
expect(result).toEqual(
expect.objectContaining({
page: 2,
perPage: 10,
pageCount: 10,
totalCount: 100
})
)
expect(result.links.self).toEqual('/items?page=2&limit=10')
expect(result.links.first).toEqual('/items?page=0&limit=10')
expect(result.links.previous).toEqual('/items?page=1&limit=10')
expect(result.links.next).toEqual('/items?page=3&limit=10')
expect(result.links.last).toEqual('/items?page=9&limit=10')
})

it('should paginate with default query', () => {
const totalCount = 100
const relativeUrl = '/items'
const query = { page: 5, limit: 10 }
const defaultQuery = { pricing: 'pro', filter: 'admin' }

const result = paginate(totalCount, relativeUrl, query, defaultQuery)

expect(result).toBeDefined()
expect(result).toEqual(
expect.objectContaining({
page: 5,
perPage: 10,
pageCount: 10,
totalCount: 100
})
)
expect(result.links.self).toEqual(
'/items?filter=admin&pricing=pro&page=5&limit=10'
)
expect(result.links.first).toEqual(
'/items?filter=admin&pricing=pro&page=0&limit=10'
)
expect(result.links.previous).toEqual(
'/items?filter=admin&pricing=pro&page=4&limit=10'
)
expect(result.links.next).toEqual(
'/items?filter=admin&pricing=pro&page=6&limit=10'
)
expect(result.links.last).toEqual(
'/items?filter=admin&pricing=pro&page=9&limit=10'
)
})

it('should paginate correctly edge cases where pervious or next is null', () => {
const totalCount = 10
const relativeUrl = '/items'
const query = { page: 0, limit: 10 }

const result = paginate(totalCount, relativeUrl, query)

expect(result).toBeDefined()
expect(result).toEqual(
expect.objectContaining({
page: 0,
perPage: 10,
pageCount: 1,
totalCount: 10
})
)
expect(result.links.self).toEqual('/items?page=0&limit=10')
expect(result.links.first).toEqual('/items?page=0&limit=10')
expect(result.links.previous).toBeNull()
expect(result.links.next).toBeNull()
expect(result.links.last).toEqual('/items?page=0&limit=10')
})

it('should not be able to paginate when limit is 0 or undefined', () => {
const totalCount = 10
const relativeUrl = '/items'
const query = { page: 0, limit: 0 }

expect(() => paginate(totalCount, relativeUrl, query)).toThrow(
'Limit is required'
)
})
})
75 changes: 75 additions & 0 deletions apps/api/src/common/paginate.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
export interface PaginatedMetadata {
page: number
perPage: number
pageCount: number
totalCount: number
links: {
self: string
first: string
previous: string | null
next: string | null
last: string
}
}

interface QueryOptions {
page: number
limit: number
sort?: string
order?: string
search?: string
}

//convert query object to query string to use in links
const getQueryString = (query: QueryOptions) => {
return Object.keys(query)
.map((key) => `${key}=${query[key]}`)
.join('&')
}

export const paginate = (
totalCount: number,
relativeUrl: string,
query: QueryOptions,
defaultQuery?: Record<string, any>
) => {
//query.limit cannot be 0 or undefined
if (!query.limit) throw new Error('Limit is required')
let defaultQueryStr = ''
if (defaultQuery) {
//sorting entries to make sure the order is consistent and predictable during tests
const sortedEntries = Object.entries(defaultQuery).sort(([keyA], [keyB]) =>
keyA.localeCompare(keyB)
)
//ignore keys with undefined values. Undefined values may occur when qury params are optional
defaultQueryStr = sortedEntries.reduce((res, [key, value]) => {
if (value !== undefined) {
res += `${key}=${value}&`
}
return res
}, '')
}

const metadata = {} as PaginatedMetadata
metadata.page = query.page
metadata.perPage = query.limit
metadata.pageCount = Math.ceil(totalCount / query.limit)
metadata.totalCount = totalCount

//create links from relativeUrl , defalutQueryStr and query of type QueryOptions
metadata.links = {
self: `${relativeUrl}?${defaultQueryStr + getQueryString(query)}`,
first: `${relativeUrl}?${defaultQueryStr + getQueryString({ ...query, page: 0 })}`,
previous:
query.page === 0
? null
: `${relativeUrl}?${defaultQueryStr + getQueryString({ ...query, page: query.page - 1 })}`,
next:
query.page === metadata.pageCount - 1
? null
: `${relativeUrl}?${defaultQueryStr + getQueryString({ ...query, page: query.page + 1 })}`,
last: `${relativeUrl}?${defaultQueryStr + getQueryString({ ...query, page: metadata.pageCount - 1 })}`
}

return metadata
}
25 changes: 22 additions & 3 deletions apps/api/src/environment/service/environment.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import { UpdateEnvironment } from '../dto/update.environment/update.environment'
import { PrismaService } from '../../prisma/prisma.service'
import createEvent from '../../common/create-event'
import { AuthorityCheckerService } from '../../common/authority-checker.service'
import { paginate } from '../../common/paginate'

@Injectable()
export class EnvironmentService {
Expand Down Expand Up @@ -171,8 +172,8 @@ export class EnvironmentService {
prisma: this.prisma
})

// Get the environments
return await this.prisma.environment.findMany({
// Get the environments for the required page
const items = await this.prisma.environment.findMany({
where: {
projectId,
name: {
Expand All @@ -195,11 +196,29 @@ export class EnvironmentService {
}
},
skip: page * limit,
take: limit,
take: Number(limit),
muntaxir4 marked this conversation as resolved.
Show resolved Hide resolved
orderBy: {
[sort]: order
}
})
// Calculate metadata for pagination
const totalCount = await this.prisma.environment.count({
where: {
projectId,
name: {
contains: search
}
}
})
const metadata = paginate(totalCount, `/environment/all/${projectId}`, {
page: Number(page),
limit: Number(limit),
sort,
order,
search
})

return { items, metadata }
}

async deleteEnvironment(user: User, environmentId: Environment['id']) {
Expand Down
13 changes: 13 additions & 0 deletions packages/api-client/src/types/environment.types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,19 @@ export interface GetAllEnvironmentsOfProjectResponse {
profilePictureUrl: string | null
}
}[]
metadata: {
muntaxir4 marked this conversation as resolved.
Show resolved Hide resolved
page: number
perPage: number
pageCount: number
totalCount: number
links: {
self: string
first: string
previous: string | null
next: string | null
last: string
}
}
}

export interface DeleteEnvironmentRequest {
Expand Down
30 changes: 27 additions & 3 deletions packages/api-client/tests/environment.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,8 +87,20 @@ describe('Get Environments Tests', () => {
}
)

expect(environments).toHaveLength(2)
expect(environments[0].name).toBe('Default')
expect(environments.items).toHaveLength(2)
expect(environments.items[0].name).toBe('Default')
expect(environments.metadata.totalCount).toEqual(2)
expect(environments.metadata.links.self).toBe(
`/environment/all/${projectId}?page=0&limit=10&sort=name&order=asc&search=`
)
expect(environments.metadata.links.first).toBe(
`/environment/all/${projectId}?page=0&limit=10&sort=name&order=asc&search=`
)
expect(environments.metadata.links.previous).toBeNull()
expect(environments.metadata.links.next).toBeNull()
expect(environments.metadata.links.last).toBe(
`/environment/all/${projectId}?page=0&limit=10&sort=name&order=asc&search=`
)
} catch (error) {
console.error(error)
process.exit(1)
Expand Down Expand Up @@ -211,7 +223,19 @@ describe('Get Environments Tests', () => {
}
)

expect(environments).toHaveLength(2)
expect(environments.items).toHaveLength(2)
expect(environments.metadata.totalCount).toEqual(2)
expect(environments.metadata.links.self).toBe(
`/environment/all/${projectId}?page=0&limit=10&sort=name&order=asc&search=`
)
expect(environments.metadata.links.first).toBe(
`/environment/all/${projectId}?page=0&limit=10&sort=name&order=asc&search=`
)
expect(environments.metadata.links.previous).toBeNull()
expect(environments.metadata.links.next).toBeNull()
expect(environments.metadata.links.last).toBe(
`/environment/all/${projectId}?page=0&limit=10&sort=name&order=asc&search=`
)
} catch (error) {
console.error(error)
process.exit(1)
Expand Down