Skip to content

Commit

Permalink
feat: add pagination to events (#102)
Browse files Browse the repository at this point in the history
  • Loading branch information
santese committed Aug 30, 2022
1 parent bfd015b commit e0384c5
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 6 deletions.
18 changes: 13 additions & 5 deletions src/lib/events/events.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { AxiosInstance } from 'axios'
import { paginatedRequest } from '../http/paginated-request'
import {
DateString,
TimelyAppConfig,
Expand All @@ -18,7 +19,7 @@ export class Events {
params.since = startDate
params.upto = endDate
}
const { data } = await this.http.get(`/${this.config.accountId}/events`, { params })
const data = await paginatedRequest(this.http, `/${this.config.accountId}/events`, params)
return data
}

Expand All @@ -29,10 +30,17 @@ export class Events {
): Promise<TimelyEvent[]> {
// Ensure given date range conforms to ISO string format
const [startDate, endDate] = [start, end].map((s) => this.ensureISOFormat(s))
const { data } = await this.http.get(
`/${this.config.accountId}/projects/${projectId}/events${
start ? `?since=${startDate}` : ''
}${end ? `&upto=${endDate}` : ''}`,
const params = {} as { since?: string; upto?: string }
if (startDate) {
params.since = startDate
}
if (endDate) {
params.upto = endDate
}
const data = await paginatedRequest(
this.http,
`/${this.config.accountId}/projects/${projectId}/events`,
params,
)
return data
}
Expand Down
28 changes: 28 additions & 0 deletions src/lib/http/paginated-request.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import type { AxiosInstance } from 'axios'

export const paginatedRequest = async (
httpAgent: AxiosInstance,
route: string,
filter?: { [index: string]: any },
per_page = 1000,
): Promise<any[]> => {
const params = {
per_page,
page: 1,
}

if (filter) Object.assign(params, { ...filter })

const finalData = []
let res: any[] = []

do {
const { data } = await httpAgent.get(route, { params })
finalData.push(...data)
res = data
params.page++
/// If the results are less than per_page, we can assume there are no more results
} while (res.length === per_page)

return finalData
}
7 changes: 6 additions & 1 deletion src/lib/reports/reports.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { AxiosInstance } from 'axios'
import { paginatedRequest } from '../http/paginated-request'
import { TimelyAppConfig } from '../types'

export class Reports {
Expand All @@ -13,7 +14,11 @@ export class Reports {
until?: string
},
) {
const { data } = await this.http.post(`/${this.config.accountId}/reports/filter`, filter)
const data = await paginatedRequest(
this.http,
`/${this.config.accountId}/reports/filter`,
filter,
)
return data
}
}

0 comments on commit e0384c5

Please sign in to comment.