Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
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
106 changes: 87 additions & 19 deletions src/hooks/useCollections.ts
Original file line number Diff line number Diff line change
@@ -1,54 +1,122 @@
import { useCallback, useEffect, useState, useMemo } from 'react';
import { type ApiError, type LoadingState } from '../types';
import type { CollectionsResponse } from '../types/stac';
import type { CollectionsPayload, CollectionsResponse, Link /*LinkBody*/ } from '../types/stac';
import debounce from '../utils/debounce';
import { useStacApiContext } from '../context';
import StacApi from '../stac-api';
import { usePreviousValue } from '../utils/usePreviousValue';

type PaginationHandler = () => void;

type StacCollectionsHook = {
collections?: CollectionsResponse,
reload: () => void,
state: LoadingState
error?: ApiError
collections?: CollectionsResponse;
reload: () => void;
state: LoadingState;
error?: ApiError;
nextPage: PaginationHandler | undefined;
previousPage: PaginationHandler | undefined;
stacApiEndpoint: StacApi | undefined;
};

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

const [ nextPageConfig, setNextPageConfig ] = useState<Link>();
const [ previousPageConfig, setPreviousPageConfig ] = useState<Link>();

const previousStacApi = usePreviousValue(stacApi);

/**
* Extracts the pagination config from the the links array of the items response
*/
const setPaginationConfig = useCallback(
(links: Link[]) => {
setNextPageConfig(links.find(({ rel }) => rel === 'next'));
setPreviousPageConfig(links.find(({ rel }) => ['prev', 'previous'].includes(rel)));
}, []
);

/**
* Resets the state and processes the results from the provided request
*/
const processRequest = useCallback((request: Promise<Response>) => {
setState('LOADING');
setError(undefined);
setNextPageConfig(undefined);
setPreviousPageConfig(undefined);

request
.then(response => response.json())
.then(data => {
setCollections(data);
if (data.links) {
setPaginationConfig(data.links);
}
})
.catch((err) => setError(err))
.finally(() => setState('IDLE'));
}, [setPaginationConfig, setCollections]);

const _getCollections = useCallback(
() => {
(payload?: CollectionsPayload) => {
if (stacApi) {
setState('LOADING');

stacApi.getCollections()
.then(response => response.json())
.then(setCollections)
.catch((err) => {
setError(err);
setCollections(undefined);
})
.finally(() => setState('IDLE'));
processRequest(stacApi.getCollections(payload));
}
},
[setCollections, stacApi]
[stacApi, processRequest]
);
const getCollections = useMemo(() => debounce(_getCollections), [_getCollections]);

/**
* Retreives a page from a paginatied item set using the provided link config.
* Executes a POST request against the `search` endpoint if pagination uses POST
* or retrieves the page items using GET against the link href
*/

const flipPage = useCallback(
(config?: any) => {
if (config.href) {
const url = new URL(config.href);
const params = url.searchParams;
const urlParams = Object.fromEntries(params.entries());
const payload = {
...urlParams,
};
getCollections(payload);
}
},
[getCollections]
);

const nextPageFn = useCallback(
() => flipPage(nextPageConfig),
[flipPage, nextPageConfig]
);

const previousPageFn = useCallback(
() => flipPage(previousPageConfig),
[flipPage, previousPageConfig]
);

useEffect(
() => {
if (stacApi && !error && !collections) {
if ((stacApi && !error && !collections) || (previousStacApi && stacApi && (stacApi !== previousStacApi))) {
getCollections();
}
},
[getCollections, stacApi, collections, error]
[getCollections, stacApi, collections, error, previousStacApi]
);

return {
collections,
reload: getCollections,
state,
error,
nextPage: nextPageConfig ? nextPageFn : undefined,
previousPage: previousPageConfig ? previousPageFn : undefined,
stacApiEndpoint: stacApi
};
}

Expand Down
28 changes: 24 additions & 4 deletions src/stac-api/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { ApiError, GenericObject } from '../types';
import type { Bbox, SearchPayload, DateRange } from '../types/stac';
import type { Bbox, SearchPayload, DateRange, CollectionsPayload } from '../types/stac';

type RequestPayload = SearchPayload;
type RequestPayload = SearchPayload | CollectionsPayload;
type FetchOptions = {
method?: string,
payload?: RequestPayload,
Expand Down Expand Up @@ -84,6 +84,21 @@ class StacApi {
return new URLSearchParams(queryObj).toString();
}

collectionsPayloadToQuery(payload: CollectionsPayload): string {
const queryObj = {};
for (const [key, value] of Object.entries(payload)) {
if (!value) continue;

if (Array.isArray(value)) {
queryObj[key] = value.join(',');
} else {
queryObj[key] = value;
}
}

return new URLSearchParams(queryObj).toString();
}

async handleError(response: Response) {
const { status, statusText } = response;
const e: ApiError = {
Expand Down Expand Up @@ -146,8 +161,13 @@ class StacApi {
}
}

getCollections(): Promise<Response> {
return this.fetch(`${this.baseUrl}/collections`);
getCollections(payload?: CollectionsPayload, headers = {}): Promise<Response> {
if (payload) {
const query = this.collectionsPayloadToQuery(payload);
return this.fetch(`${this.baseUrl}/collections?${query}`, { method: 'GET', headers });
} else {
return this.fetch(`${this.baseUrl}/collections`);
}
}

get(href: string, headers = {}): Promise<Response> {
Expand Down
4 changes: 4 additions & 0 deletions src/types/stac.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@ export type SearchPayload = {
sortby?: Sortby[]
}

export type CollectionsPayload = {
offset?: number;
}

export type LinkBody = SearchPayload & {
merge?: boolean
}
Expand Down
9 changes: 9 additions & 0 deletions src/utils/usePreviousValue.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { useRef, useEffect } from 'react';

export const usePreviousValue = <T>(value: T) => {
const ref = useRef<T>(value);
useEffect(() => {
ref.current = value;
}, [value]);
return ref.current;
};