Skip to content
Draft
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
84 changes: 83 additions & 1 deletion src/hooks/useCollections.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,12 @@ describe('useCollections', () => {
await waitForNextUpdate();
await waitForNextUpdate();
expect(fetch.mock.calls[1][0]).toEqual(
'https://fake-stac-api.net/collections?limit=10'
'https://fake-stac-api.net/collections'
);
expect(result.current.collections).toEqual({ data: '12345' });
expect(result.current.state).toEqual('IDLE');
expect(result.current.nextPage).toEqual(undefined);
expect(result.current.prevPage).toEqual(undefined);
});

it('reloads collections', async () => {
Expand Down Expand Up @@ -94,4 +96,84 @@ describe('useCollections', () => {
detail: 'Wrong query'
});
});

it('queries collections with pagination', async () => {
const mockPage1 = {
data: '12345',
links: [
{ rel: 'next', href: 'https://fake-stac-api.net/collections?page=2' }
]
};

const mockPage2 = {
data: '67890',
links: [
{ rel: 'next', href: 'https://fake-stac-api.net/collections?page=3' },
{ rel: 'prev', href: 'https://fake-stac-api.net/collections?page=1' }
]
};

const mockPage3 = {
data: 'abcde',
links: [
{ rel: 'prev', href: 'https://fake-stac-api.net/collections?page=2' }
]
};

fetch
.mockResponseOnce(JSON.stringify({ links: [] }), {
url: 'https://fake-stac-api.net'
})
.mockResponses(
JSON.stringify(mockPage1),
JSON.stringify(mockPage2),
JSON.stringify(mockPage3),
JSON.stringify(mockPage2)
);


const { result, waitForNextUpdate } = renderHook(() => useCollections(), {
wrapper
});
await waitForNextUpdate();
await waitForNextUpdate();
expect(fetch.mock.calls[1][0]).toEqual(
'https://fake-stac-api.net/collections'
);
expect(result.current.collections).toEqual(mockPage1);
expect(result.current.state).toEqual('IDLE');
expect(typeof result.current.nextPage).toBe('function');
expect(result.current.prevPage).toEqual(undefined);

act(() => result.current.nextPage?.());
await waitForNextUpdate();

expect(fetch.mock.calls[2][0]).toEqual(
'https://fake-stac-api.net/collections?page=2'
);
expect(result.current.collections).toEqual(mockPage2);
expect(result.current.state).toEqual('IDLE');
expect(typeof result.current.prevPage).toBe('function');
expect(typeof result.current.nextPage).toBe('function');

act(() => result.current.nextPage?.());
await waitForNextUpdate();
expect(fetch.mock.calls[3][0]).toEqual(
'https://fake-stac-api.net/collections?page=3'
);
expect(result.current.collections).toEqual(mockPage3);
expect(result.current.state).toEqual('IDLE');
expect(typeof result.current.prevPage).toBe('function');
expect(result.current.nextPage).toEqual(undefined);

act(() => result.current.prevPage?.());
await waitForNextUpdate();
expect(fetch.mock.calls[4][0]).toEqual(
'https://fake-stac-api.net/collections?page=2'
);
expect(result.current.collections).toEqual(mockPage2);
expect(result.current.state).toEqual('IDLE');
expect(typeof result.current.prevPage).toBe('function');
expect(typeof result.current.nextPage).toBe('function');
});
});
53 changes: 21 additions & 32 deletions src/hooks/useCollections.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,36 +11,31 @@ type StacCollectionsHook = {
error?: ApiError;
nextPage?: () => void;
prevPage?: () => void;
setOffset: (newOffset: number) => void;
setCurrentUrl: (url: string | undefined) => void;
};

export default function useCollections(opts?: {
limit?: number;
initialOffset?: number;
}): StacCollectionsHook {
const { limit = 10, initialOffset = 0 } = opts || {};

export default function useCollections(): StacCollectionsHook {
const { stacApi, collections, setCollections } = useStacApiContext();
const [state, setState] = useState<LoadingState>('IDLE');
const [error, setError] = useState<ApiError>();

const [offset, setOffset] = useState(initialOffset);
const [nextUrl, setNextUrl] = useState<string | undefined>();
const [prevUrl, setPrevUrl] = useState<string | undefined>();
const [currentUrl, setCurrentUrl] = useState<string | undefined>();

const [hasNext, setHasNext] = useState(false);
const [hasPrev, setHasPrev] = useState(false);

const _getCollections = useCallback(
async (offset: number, limit: number) => {
async (url?: string) => {
if (stacApi) {
setState('LOADING');

try {
const res = await stacApi.getCollections({ limit, offset });
const res = await stacApi.getCollections(url);
const data: CollectionsResponse = await res.json();

setHasNext(!!data.links?.find((l) => l.rel === 'next'));
setHasPrev(
!!data.links?.find((l) => ['prev', 'previous'].includes(l.rel))
setNextUrl(data.links?.find((l) => l.rel === 'next')?.href);
setPrevUrl(
data.links?.find((l) => ['prev', 'previous'].includes(l.rel))?.href
);

setCollections(data);
Expand All @@ -56,34 +51,28 @@ export default function useCollections(opts?: {
);

const getCollections = useCallback(
(offset: number, limit: number) =>
debounce(() => _getCollections(offset, limit))(),
(url?: string) => debounce(() => _getCollections(url))(),
[_getCollections]
);

const nextPage = useCallback(() => {
setOffset(offset + limit);
}, [offset, limit]);

const prevPage = useCallback(() => {
setOffset(offset - limit);
}, [offset, limit]);
const nextPage = useCallback(() => setCurrentUrl(nextUrl), [nextUrl]);
const prevPage = useCallback(() => setCurrentUrl(prevUrl), [prevUrl]);

useEffect(() => {
if (stacApi && !error && !collections) {
getCollections(offset, limit);
if (stacApi && !error) {
getCollections(currentUrl);
}
}, [getCollections, stacApi, collections, error, offset, limit]);
}, [getCollections, stacApi, error, currentUrl]);

return {
collections,
reload: useCallback(
() => getCollections(offset, limit),
[getCollections, offset, limit]
() => getCollections(currentUrl),
[getCollections, currentUrl]
),
nextPage: hasNext ? nextPage : undefined,
prevPage: hasPrev ? prevPage : undefined,
setOffset,
nextPage: nextUrl ? nextPage : undefined,
prevPage: prevUrl ? prevPage : undefined,
setCurrentUrl,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we need to expose this? It feels like this should only be used internally.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually, thinking about it. Do we need the currentUrl state at all? It seems like it's only needed the set the prev/next page URLs, but couldn't we call getCollections directly from the nextPage/prevPage callbacks?

const nextPage = useCallback(() => getCollections(nextUrl), [nextUrl]);
const prevPage = useCallback(() => getCollections(prevUrl), [prevUrl]);

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is also being used for the reload.

state,
error
};
Expand Down
4 changes: 2 additions & 2 deletions src/hooks/useStacApi.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ describe('useStacApi', () => {
await waitForNextUpdate();
await waitForNextUpdate();
expect(fetch.mock.calls[1][0]).toEqual(
'https://fake-stac-api.net/collections?limit=10'
'https://fake-stac-api.net/collections'
);
});

Expand All @@ -35,7 +35,7 @@ describe('useStacApi', () => {
await waitForNextUpdate();
await waitForNextUpdate();
expect(fetch.mock.calls[1][0]).toEqual(
'https://fake-stac-api.net/redirect/collections?limit=10'
'https://fake-stac-api.net/redirect/collections'
);
});
});
15 changes: 2 additions & 13 deletions src/stac-api/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -159,19 +159,8 @@ class StacApi {
}
}

getCollections(options?: {
limit: number;
offset: number;
}): Promise<Response> {
const { limit, offset } = options || {};
const query = new URLSearchParams();
if (limit) query.set('limit', limit.toString());
if (offset) query.set('offset', offset.toString());
return this.fetch(
`${this.baseUrl}/collections${
query.toString() ? `?${query.toString()}` : ''
}`
);
getCollections(url?: string): Promise<Response> {
return this.fetch(url || `${this.baseUrl}/collections`);
}

getCollection(id: string): Promise<Response> {
Expand Down