Skip to content

Commit

Permalink
feat: add useRoadizHydraCollectionFetch
Browse files Browse the repository at this point in the history
  • Loading branch information
timothejoubert committed Jun 3, 2024
1 parent 803b889 commit 3e0e421
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
8 changes: 8 additions & 0 deletions composables/use-roadiz-hydra-collection-fetch.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import type { FetchOptions } from 'ofetch'
import { hydraCollectionFetch } from '~/utils/hydra-collection-fetch'

export function useRoadizHydraCollectionFetch<T>(url: string, request?: FetchOptions) {
const fetch = useRoadizFetchFactory()

return hydraCollectionFetch<T>(url, request, fetch)
}
31 changes: 31 additions & 0 deletions utils/hydra-collection-fetch.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import type { HydraCollection } from '@roadiz/types'
import type { FetchOptions } from 'ofetch'

// Fetch hydra collection recursively
export async function hydraCollectionFetch<T>(url: string, request?: FetchOptions, fetch = $fetch) {
const result = [] as Array<T>
let page = request?.params?.page || 1
let active = true

do {
const response = await fetch<HydraCollection<T>>(url, {
...request,
method: 'GET',
params: {
...request?.params,
page,
},
})

if (response?.['hydra:member']) {
result.push(...response['hydra:member'])

active = !!response?.['hydra:view']?.['hydra:next']
page++
} else {
active = false
}
} while (active)

return result
}

0 comments on commit 3e0e421

Please sign in to comment.