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