| 1 |
/** |
| 2 |
* WordPress dependencies. |
| 3 |
*/ |
| 4 |
import { useCallback, useRef } from '@wordpress/element'; |
| 5 |
|
| 6 |
/** |
| 7 |
* Internal dependencies. |
| 8 |
*/ |
| 9 |
import { generateRequestId } from '../../utils/helpers'; |
| 10 |
|
| 11 |
/** |
| 12 |
* Get a callback function for retrieving search results. |
| 13 |
* |
| 14 |
* @param {string} apiHost API host. |
| 15 |
* @param {string} apiEndpoint API endpoint. |
| 16 |
* @param {string} Authorization Authorization header. |
| 17 |
* @param {Function} onAuthError Function to run when request authentication fails. |
| 18 |
* @param {string} requestIdBase Base of Request IDs. |
| 19 |
* @returns {Function} Function for retrieving search results. |
| 20 |
*/ |
| 21 |
export const useFetchResults = ( |
| 22 |
apiHost, |
| 23 |
apiEndpoint, |
| 24 |
Authorization, |
| 25 |
onAuthError, |
| 26 |
requestIdBase = '', |
| 27 |
) => { |
| 28 |
const abort = useRef(new AbortController()); |
| 29 |
const request = useRef(null); |
| 30 |
const onAuthErrorRef = useRef(onAuthError); |
| 31 |
|
| 32 |
/** |
| 33 |
* Get new search results from the API. |
| 34 |
* |
| 35 |
* @param {URLSearchParams} urlParams Query arguments. |
| 36 |
* @returns {Promise} Request promise. |
| 37 |
*/ |
| 38 |
const fetchResults = async (urlParams) => { |
| 39 |
const url = `${apiHost}${apiEndpoint}?${urlParams.toString()}`; |
| 40 |
|
| 41 |
abort.current.abort(); |
| 42 |
abort.current = new AbortController(); |
| 43 |
|
| 44 |
const headers = { |
| 45 |
Accept: 'application/json', |
| 46 |
Authorization, |
| 47 |
}; |
| 48 |
|
| 49 |
const requestId = generateRequestId(requestIdBase); |
| 50 |
if (requestId) { |
| 51 |
headers['X-ElasticPress-Request-ID'] = requestId; |
| 52 |
} |
| 53 |
|
| 54 |
request.current = fetch(url, { |
| 55 |
signal: abort.current.signal, |
| 56 |
headers, |
| 57 |
}) |
| 58 |
.then((response) => { |
| 59 |
if (onAuthErrorRef.current && !response.ok) { |
| 60 |
onAuthErrorRef.current(); |
| 61 |
} |
| 62 |
|
| 63 |
return response.json(); |
| 64 |
}) |
| 65 |
.catch((error) => { |
| 66 |
if (error?.name !== 'AbortError' && !request.current) { |
| 67 |
throw error; |
| 68 |
} |
| 69 |
}) |
| 70 |
.finally(() => { |
| 71 |
request.current = null; |
| 72 |
}); |
| 73 |
|
| 74 |
return request.current; |
| 75 |
}; |
| 76 |
|
| 77 |
return useCallback(fetchResults, [apiHost, apiEndpoint, Authorization, requestIdBase]); |
| 78 |
}; |
| 79 |
|