forked from didirus/AstralRinth
87c86c7d0d
* Reapply "fix: start swapping useBaseFetch usages to api-client" This reverts commit f4f33db7019ea861addb2c66c204d736800b7b6c. * fix: bugs * fix: analytics * fix: lint
37 lines
931 B
TypeScript
37 lines
931 B
TypeScript
function segmentData<T>(data: T[], segmentSize: number): T[][] {
|
|
return data.reduce((acc: T[][], curr, index) => {
|
|
const segment = Math.floor(index / segmentSize)
|
|
|
|
if (!acc[segment]) {
|
|
acc[segment] = []
|
|
}
|
|
acc[segment].push(curr)
|
|
return acc
|
|
}, [])
|
|
}
|
|
|
|
export function fetchSegmented<T>(
|
|
data: T[],
|
|
createUrl: (ids: T[]) => string,
|
|
options = {},
|
|
segmentSize = 800,
|
|
): Promise<any> {
|
|
return Promise.all(
|
|
segmentData(data, segmentSize).map((ids) => useBaseFetch(createUrl(ids), options)),
|
|
).then((results) => results.flat())
|
|
}
|
|
|
|
export function fetchSegmentedWith<TId, TResult>(
|
|
data: TId[],
|
|
fetchFn: (ids: TId[]) => Promise<TResult[]>,
|
|
segmentSize = 800,
|
|
): Promise<TResult[]> {
|
|
return Promise.all(segmentData(data, segmentSize).map((ids) => fetchFn(ids))).then((results) =>
|
|
results.flat(),
|
|
)
|
|
}
|
|
|
|
export function asEncodedJsonArray<T>(data: T[]): string {
|
|
return encodeURIComponent(JSON.stringify(data))
|
|
}
|