import debug from 'debug' ; import { OptionsOfJSONResponseBody } from 'got' ; import { TwilioServerlessApiClient } from '../../client' ; import { BaseList } from '../../types' ; import { ClientApiError } from '../../utils/error' ; const log = debug ( 'twilio-serverless-api:utils:pagination' ) ; export async function getPaginatedResource < TList extends BaseList < string > , TEntry > ( client , url , opts = { responseType : 'json' } ) { let result = [ ] ; opts = { ... opts , } ; let nextPageUrl = url ; do { try { if ( nextPageUrl . startsWith ( 'http' ) ) { opts . prefixUrl = '' ; } const resp = await client . request ( 'get' , nextPageUrl , opts ) ; const body = resp . body as TList ; nextPageUrl = body . meta . next_page_url ; const entries = body [ body . meta . key ] as TEntry [ ] ; result = [ ... result , ... entries ] ; } catch ( err ) { log ( '%O' , new ClientApiError ( err ) ) ; if ( nextPageUrl === url ) { throw err ; } else { break ; } } } while ( nextPageUrl !== null ) ; return result ; }