Skip to content

Commit

Permalink
feat: add fetching rest.maxResultsAbsolute
Browse files Browse the repository at this point in the history
  • Loading branch information
usamaidrsk committed Jan 17, 2025
1 parent 1b14984 commit 8bf9ed2
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 10 deletions.
17 changes: 7 additions & 10 deletions src/hooks/useConcepts.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { useMemo } from 'react';
import useSWRInfinite from 'swr/infinite';
import { type FetchResponse, openmrsFetch, type OpenmrsResource, restBaseUrl } from '@openmrs/esm-framework';
import { useRestApiMaxResults } from './useRestApiMaxResults';

type ConceptFetchResponse = FetchResponse<{ results: Array<OpenmrsResource> }>;

Expand All @@ -12,25 +13,21 @@ export function useConcepts(references: Set<string>): {
isLoading: boolean;
error: Error | undefined;
} {
const chunkSize = 100;
const { maxResults } = useRestApiMaxResults();
const totalCount = references.size;
const totalPages = Math.ceil(totalCount / chunkSize);
const totalPages = Math.ceil(totalCount / maxResults);

const getUrl = (index, prevPageData: ConceptFetchResponse) => {
const getUrl = (index: number, prevPageData: ConceptFetchResponse) => {
if (index >= totalPages) {
return null;
}

if (!chunkSize) {
return null;
}

const start = index * chunkSize;
const end = start + chunkSize;
const start = index * maxResults;
const end = start + maxResults;
const referenceChunk = Array.from(references).slice(start, end);
return `${restBaseUrl}/concept?references=${referenceChunk.join(
',',
)}&v=${conceptRepresentation}&limit=${chunkSize}`;
)}&v=${conceptRepresentation}&limit=${maxResults}`;
};

const { data, error, isLoading } = useSWRInfinite<ConceptFetchResponse, Error>(getUrl, openmrsFetch, {
Expand Down
35 changes: 35 additions & 0 deletions src/hooks/useRestApiMaxResults.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { useMemo } from 'react';
import useSWR from 'swr';
import { type FetchResponse, openmrsFetch, restBaseUrl } from '@openmrs/esm-framework';

type GlobalPropertyResponse = FetchResponse<{
results: Array<{ property: string; value: string }>;
}>;

const DEFAULT_CHUNK_SIZE = 100;

export function useRestApiMaxResults() {
const { data, error, isLoading } = useSWR<GlobalPropertyResponse, Error>(
`${restBaseUrl}/systemsetting?q=webservices.rest.maxResultsAbsolute&v=custom:(property,value)`,
openmrsFetch,
);

const maxResults = useMemo(() => {
try {
const maxResultsValue = data?.data.results.find(
(prop) => prop.property === 'webservices.rest.maxResultsAbsolute',
)?.value;

const parsedValue = parseInt(maxResultsValue ?? '');
return !isNaN(parsedValue) && parsedValue > 0 ? parsedValue : DEFAULT_CHUNK_SIZE;
} catch {
return DEFAULT_CHUNK_SIZE;
}
}, [data]);

return {
maxResults,
error,
isLoading,
};
}

0 comments on commit 8bf9ed2

Please sign in to comment.