Skip to content

Commit

Permalink
fix: paging parsing issues (#728)
Browse files Browse the repository at this point in the history
* updates URL parse to work with relative path

* update paging header recognition to be case insensitive

* Simplify `offset` and `limit` value extraction

Co-authored-by: John Kaster <kaster@google.com>
  • Loading branch information
annguy3n and jkaster authored Jul 1, 2021
1 parent caa3291 commit f8eec43
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 6 deletions.
13 changes: 13 additions & 0 deletions packages/sdk-rtl/src/paging.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,19 @@ describe('paging', () => {
expect(actual.options?.timeout).toEqual(99)
})

it('works on relative url', async () => {
const actual = await pager(sdk, () =>
mockRawResponseSuccess(
transport,
mockedRows,
mockRawResponse('/api/4.0/alerts/search?fields=id&limit=3&offset=0')
)
)
expect(actual).toBeDefined()
expect(actual.limit).toEqual(3)
expect(actual.offset).toEqual(0)
})

it('supports paging', async () => {
const paged = await pager(sdk, () =>
mockRawResponseSuccess(transport, mockedRows, mockRawResponse())
Expand Down
19 changes: 13 additions & 6 deletions packages/sdk-rtl/src/paging.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ import {
import { IAPIMethods } from './apiMethods'
import { BaseTransport } from './baseTransport'

export const LinkHeader = 'link'
export const LinkHeader = 'Link'
export const TotalCountHeader = 'X-Total-Count'

/**
Expand Down Expand Up @@ -257,7 +257,7 @@ export class Paging<TSuccess extends ILength, TError>
this.transport.observer = saved
}
if (Object.keys(raw).length === 0 || Object.keys(raw.headers).length === 0)
throw new Error('No paging headers were found')
return Promise.reject(new Error('No paging headers were found'))
this.parse(raw)
return this
}
Expand Down Expand Up @@ -362,21 +362,28 @@ export class Paging<TSuccess extends ILength, TError>
return result
}

static findHeader(raw: IRawResponse, name: string) {
return (
raw.headers[name] ||
raw.headers[name.toLowerCase()] ||
raw.headers[name.toUpperCase()]
)
}

parse(raw: IRawResponse): IPager<TSuccess, TError> {
const req = new URL(raw.url)
const params = req.searchParams
const params = new URLSearchParams(raw.url)
this.limit = Paging.paramDefault(params.get('limit'), -1)
this.offset = Paging.paramDefault(
params.get('offset'),
this.limit > 0 ? 0 : -1
)
const linkHeader = raw.headers.link || raw.headers.Link || raw.headers.LINK
const linkHeader = Paging.findHeader(raw, LinkHeader)
if (linkHeader) {
this.links = linkHeaderParser(linkHeader)
} else {
this.links = {}
}
const totalHeader = raw.headers[TotalCountHeader]
const totalHeader = Paging.findHeader(raw, TotalCountHeader)
if (totalHeader) {
this.total = parseInt(totalHeader.trim(), 10)
} else {
Expand Down

0 comments on commit f8eec43

Please sign in to comment.