UNPKG

ra-core

Version:

Core components of react-admin, a frontend Framework for building admin applications on top of REST services, using ES6, React

303 lines (302 loc) 11.7 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.useGetManyAggregate = void 0; const react_1 = require("react"); const react_query_1 = require("@tanstack/react-query"); const union_js_1 = __importDefault(require("lodash/union.js")); const useDataProvider_1 = require("./useDataProvider.cjs"); const util_1 = require("../util/index.cjs"); /** * Call the dataProvider.getMany() method and return the resolved result * as well as the loading state. * * The return value updates according to the request state: * * - start: { isPending: true, isFetching: true, refetch } * - success: { data: [data from response], isPending: false, isFetching: false, refetch } * - error: { error: [error from response], isPending: false, isFetching: false, refetch } * * This hook will return the cached result when called a second time * with the same parameters, until the response arrives. * * This hook aggregates and deduplicates calls to the same resource, so for instance, if an app calls: * * useGetManyAggregate('tags', [1, 2, 3]); * useGetManyAggregate('tags', [3, 4]); * * during the same tick, the hook will only call the dataProvider once with the following parameters: * * dataProvider.getMany('tags', [1, 2, 3, 4]) * * @param resource The resource name, e.g. 'posts' * @param {Params} params The getMany parameters { ids, meta } * @param {Object} options Options object to pass to the dataProvider. * @param {boolean} options.enabled Flag to conditionally run the query. If it's false, the query will not run * @param {Function} options.onSuccess Side effect function to be executed upon success, e.g. { onSuccess: { refresh: true } } * @param {Function} options.onError Side effect function to be executed upon failure, e.g. { onError: error => notify(error.message) } * * @typedef Params * @prop params.ids The ids to get, e.g. [123, 456, 789] * @prop params.meta Optional meta parameters * @returns The current request state. Destructure as { data, error, isPending, isFetching, refetch }. * * @example * * import { useGetManyAggregate, useRecordContext } from 'react-admin'; * * const PostTags = () => { * const record = useRecordContext(); * const { data, isPending, error } = useGetManyAggregate('tags', { ids: record.tagIds }); * if (isPending) { return <Loading />; } * if (error) { return <p>ERROR</p>; } * return ( * <ul> * {data.map(tag => ( * <li key={tag.id}>{tag.name}</li> * ))} * </ul> * ); * }; */ const useGetManyAggregate = (resource, params, options = {}) => { const dataProvider = (0, useDataProvider_1.useDataProvider)(); const queryClient = (0, react_query_1.useQueryClient)(); const { onError = noop, onSuccess = noop, onSettled = noop, enabled, ...queryOptions } = options; const onSuccessEvent = (0, util_1.useEvent)(onSuccess); const onErrorEvent = (0, util_1.useEvent)(onError); const onSettledEvent = (0, util_1.useEvent)(onSettled); const { ids, meta } = params; const placeholderData = (0, react_1.useMemo)(() => { const records = (Array.isArray(ids) ? ids : [ids]).map(id => queryClient.getQueryData([ resource, 'getOne', { id: String(id), meta }, ])); if (records.some(record => record === undefined)) { return undefined; } else { return records; } }, [ids, queryClient, resource, meta]); const result = (0, react_query_1.useQuery)({ queryKey: [ resource, 'getMany', { ids: (Array.isArray(ids) ? ids : [ids]).map(id => String(id)), meta, }, ], queryFn: queryParams => new Promise((resolve, reject) => { if (!ids || ids.length === 0) { // no need to call the dataProvider return resolve([]); } // debounced / batched fetch return callGetManyQueries({ resource, ids, meta, resolve, reject, dataProvider, queryClient, signal: dataProvider.supportAbortSignal === true ? queryParams.signal : undefined, }); }), placeholderData, enabled: enabled ?? ids != null, retry: false, ...queryOptions, }); const metaValue = (0, react_1.useRef)(meta); const resourceValue = (0, react_1.useRef)(resource); (0, react_1.useEffect)(() => { metaValue.current = meta; }, [meta]); (0, react_1.useEffect)(() => { resourceValue.current = resource; }, [resource]); (0, react_1.useEffect)(() => { if (result.data === undefined || result.error != null || result.isFetching) return; // optimistically populate the getOne cache (result.data ?? []).forEach(record => { queryClient.setQueryData([ resourceValue.current, 'getOne', { id: String(record.id), meta: metaValue.current }, ], oldRecord => oldRecord ?? record); }); onSuccessEvent(result.data); }, [ queryClient, onSuccessEvent, result.data, result.error, result.isFetching, ]); (0, react_1.useEffect)(() => { if (result.error == null || result.isFetching) return; onErrorEvent(result.error); }, [onErrorEvent, result.error, result.isFetching]); (0, react_1.useEffect)(() => { if (result.status === 'pending' || result.isFetching) return; onSettledEvent(result.data, result.error); }, [ onSettledEvent, result.data, result.error, result.status, result.isFetching, ]); return result; }; exports.useGetManyAggregate = useGetManyAggregate; /** * Batch all calls to a function into one single call with the arguments of all the calls. * * @example * let sum = 0; * const add = (args) => { sum = args.reduce((arg, total) => total + arg, 0); }; * const addBatched = batch(add); * addBatched(2); * addBatched(8); * // add will be called once with arguments [2, 8] * // and sum will be equal to 10 */ const batch = fn => { let capturedArgs = []; let timeout = null; return (arg) => { capturedArgs.push(arg); if (timeout) clearTimeout(timeout); timeout = setTimeout(() => { timeout = null; fn([...capturedArgs]); capturedArgs = []; }, 0); }; }; /** * Group and execute all calls to the dataProvider.getMany() method for the current tick * * Thanks to batch(), this function executes at most once per tick, * whatever the number of calls to useGetManyAggregate(). */ const callGetManyQueries = batch((calls) => { const dataProvider = calls[0].dataProvider; const queryClient = calls[0].queryClient; /** * Aggregate calls by resource and meta * * callsByResourceAndMeta will look like: * { * 'posts|{"test":true}': [{ resource, ids, resolve, reject, dataProvider, queryClient }, ...], * 'posts|{"test":false}': [{ resource, ids, resolve, reject, dataProvider, queryClient }, ...], * tags: [{ resource, ids, resolve, reject, dataProvider, queryClient }, ...], * } */ const callsByResourceAndMeta = calls.reduce((acc, callArgs) => { const key = `${callArgs.resource}|${JSON.stringify(callArgs.meta)}`; if (!acc[key]) { acc[key] = []; } acc[key].push(callArgs); return acc; }, {}); /** * For each resource/meta association, aggregate ids and call dataProvider.getMany() once */ Object.keys(callsByResourceAndMeta).forEach(resource => { const callsForResource = callsByResourceAndMeta[resource]; const uniqueResource = callsForResource.reduce((acc, { resource }) => resource || acc, '' // Should never happen as we always have a resource in callArgs but makes TS happy ); /** * Extract ids from queries, aggregate and deduplicate them * * @example from [[1, 2], [2, null, 3], [4, null]] to [1, 2, 3, 4] */ const aggregatedIds = callsForResource .reduce((acc, { ids }) => (0, union_js_1.default)(acc, ids), []) // concat + unique .filter(v => v != null && v !== ''); // remove null values const uniqueMeta = callsForResource.reduce((acc, { meta }) => meta || acc, undefined); if (aggregatedIds.length === 0) { // no need to call the data provider if all the ids are null callsForResource.forEach(({ resolve }) => { resolve([]); }); return; } const callThatHasAllAggregatedIds = callsForResource.find(({ ids, signal }) => JSON.stringify(ids) === JSON.stringify(aggregatedIds) && !signal?.aborted); if (callThatHasAllAggregatedIds) { // There is only one call (no aggregation), or one of the calls has the same ids as the sum of all calls. // Either way, we can't trigger a new fetchQuery with the same signature, as it's already pending. // Therefore, we reply with the dataProvider const { dataProvider, resource, ids, meta, signal } = callThatHasAllAggregatedIds; dataProvider .getMany(resource, { ids, meta, signal }) .then(({ data }) => data) .then(data => { // We must then resolve all the pending calls with the data they requested callsForResource.forEach(({ ids, resolve }) => { resolve(data.filter(record => ids .map(id => String(id)) .includes(String(record.id)))); }); }, error => { // All pending calls must also receive the error callsForResource.forEach(({ reject }) => { reject(error); }); }); return; } /** * Call dataProvider.getMany() with the aggregatedIds, * and resolve each of the promises using the results */ queryClient .fetchQuery({ queryKey: [ uniqueResource, 'getMany', { ids: aggregatedIds.map(id => String(id)), meta: uniqueMeta, }, ], queryFn: queryParams => dataProvider .getMany(uniqueResource, { ids: aggregatedIds, meta: uniqueMeta, signal: dataProvider.supportAbortSignal === true ? queryParams.signal : undefined, }) .then(({ data }) => data), }) .then(data => { callsForResource.forEach(({ ids, resolve }) => { resolve(data.filter(record => ids .map(id => String(id)) .includes(String(record.id)))); }); }) .catch(error => callsForResource.forEach(({ reject }) => reject(error))); }); }); const noop = () => undefined; //# sourceMappingURL=useGetManyAggregate.js.map