Skip to content
Merged
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
13,834 changes: 3,861 additions & 9,973 deletions package-lock.json

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@
"prepare": "husky"
},
"dependencies": {
"@reduxjs/toolkit": "^2.5.0",
"@reduxjs/toolkit": "^2.6.0",
"axios": "^1.7.9",
"class-transformer": "^0.5.1",
"core-js": "^3.40.0",
Expand Down
46 changes: 45 additions & 1 deletion src/create-entity-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ import {
* @param {((pagination: Pagination, request: TSearchRequest) => number) | undefined} [options.getCurrentPage=((pagination) => pagination.currentPage)] - The function to get current page.
* @returns {Omit<EntityApi<TEntity, TSearchRequest, TEntityRequest, TSearchResponse, typeof omitEndpoints>, keyof EntityApiCustomHooks> & EntityApiCustomHooks<TEntity, TSearchRequest, TSearchResponse>} The entity API.
*/

export function createEntityApi<
TEntity extends BaseEntity,
TSearchRequest extends PaginationRequest = PaginationRequest,
Expand Down Expand Up @@ -179,7 +180,6 @@ export function createEntityApi<
},
providesTags: (response) => getEntityTags(entityName, response, getEntityId),
}),

/**
* Creates a query endpoint for infinite searching entities. Behaves similar to `search`:
* - A query endpoint that requests `GET /{baseEndpoint}` for searching entities.
Expand Down Expand Up @@ -231,6 +231,50 @@ export function createEntityApi<
}
},
}),
/**
* Creates a query endpoint for infinite searching entities.
* - A query endpoint that requests `GET /{baseEndpoint}` for searching entities.
* - Accepts request params described by `entitySearchRequestConstructor` and returns `entitySearchResponseConstructor` extending `PaginationRequest` and `PaginationResponse` respectively.
* But accumulates data from newly requested pages.
* This query can be used with `useSearchPaginatedInfiniteQuery` hook to implement infinite scrolling lists.
* It supports loading data in both directions using `fetchNextPage` and `fetchPreviousPage` callbacks, and provides other useful props.
*
* @param {TSearchRequest} params - The parameters for searching the entities.
* @return {Promise<InfiniteData<TSearchResponse, number>>} A promise that resolves to the search result.
*/
searchPaginated: builder.infiniteQuery<TSearchResponse, TSearchRequest, number>({
infiniteQueryOptions: {
initialPageParam: 1,

getNextPageParam: (lastPage, _allPages, lastPageParam) => lastPageParam < lastPage?.pagination.lastPage ? lastPageParam + 1 : undefined,
},
query: ({ queryArg, pageParam }) => {
return {
method: 'get',
url: baseEndpoint,
params: prepareRequestParams({ ...queryArg, page: pageParam }, entitySearchRequestConstructor),
};
},
transformResponse: (response, _, { queryArg }) => {
const { data, pagination } = plainToInstance(entitySearchResponseConstructor, response);

return {
minPage: pagination.currentPage,
data: data.map((item) => createEntityInstance<TEntity>(entityConstructor, item)),
pagination: { ...pagination, currentPage: getCurrentPage(pagination, queryArg) },
} as TSearchResponse & { minPage?: number };
},
providesTags: (data) => {
return data
? [
{ type: entityName, id: EntityTagID.LIST },
...data.pages
.map((response) => response.data.map((item) => ({ type: entityName, id: getEntityId(item) })))
.flat(),
]
: [];
},
}),

/**
* Creates a query endpoint that requests `GET /{baseEndpoint}/{id}` to fetch single entity data by ID.
Expand Down
2 changes: 1 addition & 1 deletion src/hooks/use-infinite-query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { BaseEntity, PaginationRequest, PaginationResponse } from '../models';
import { EntityApi, EntityMutationEndpointName } from '../types';

/**
* @deprecated This hook will be removed. Instead, use 'useSearchInfiniteQuery' hook in your entity API directly
* @deprecated This hook will be removed. Instead, use 'useSearchPaginatedInfiniteQuery' hook in your entity API directly
*/
export const useInfiniteQuery = <
TEntity extends BaseEntity,
Expand Down
15 changes: 15 additions & 0 deletions src/types/entity-api.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import {
Api,
InfiniteQueryDefinition,
MutationDefinition,
QueryDefinition,
coreModuleName,
Expand All @@ -21,6 +22,20 @@ export type EntityEndpointsDefinitions<
create: MutationDefinition<Partial<TEntity>, BaseQueryFunction, string, TEntity>;
search: QueryDefinition<TSearchRequest, BaseQueryFunction, string, TSearchResponse>;
searchInfinite: QueryDefinition<TSearchRequest, BaseQueryFunction, string, TSearchResponse & { minPage?: number }>;
Copy link
Collaborator

Choose a reason for hiding this comment

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

I think we should mark this old endpoint as deprecated

/**
* @deprecated This endpoint will be removed. Instead, use 'useSearchPaginatedInfiniteQuery' hook in your entity API
*/
searchPaginated: InfiniteQueryDefinition<
TSearchRequest,
number,
BaseQueryFunction,
string,
TSearchResponse & {
minPage?: number;
},
string,
unknown
>;
get: QueryDefinition<{ id: TEntity['id']; params?: TEntityRequest }, BaseQueryFunction, string, TEntity>;
update: MutationDefinition<EntityPartial<TEntity>, BaseQueryFunction, string, EntityPartial<TEntity>>;
delete: MutationDefinition<number, BaseQueryFunction, string, void>;
Expand Down
50 changes: 45 additions & 5 deletions src/utils/create-entity-api-utils.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { PatchCollection } from '@reduxjs/toolkit/src/query/core/buildThunks';
import { InfiniteData } from '@reduxjs/toolkit/query';
import { MaybeDrafted, PatchCollection } from '@reduxjs/toolkit/src/query/core/buildThunks';
import { ClassConstructor } from 'class-transformer';
import { EntityTagID } from '../enums';
import { BaseEntity, EntityRequest, PaginationRequest, PaginationResponse } from '../models';
Expand All @@ -10,6 +11,7 @@ import {
EntityQueryEndpointName,
} from '../types';
import { createEntityInstance } from './create-entity-instance';
import { findEntityInPages } from './find-entity-in-pages';
import { mergeEntity } from './merge-entity';

export const createEntityApiUtils = <
Expand Down Expand Up @@ -66,8 +68,17 @@ export const createEntityApiUtils = <

const action = api.util.updateQueryData(
endpointName as EntityQueryEndpointName,
originalArgs as any,
(endpointData) => {
originalArgs as never,
(data) => {
const endpointData = data as MaybeDrafted<
| TEntity
| TSearchResponse
| (TSearchResponse & {
minPage?: number;
})
| InfiniteData<TSearchResponse, number>
>;

if ('data' in endpointData && Array.isArray(endpointData.data)) {
const existingItemIndex = endpointData.data.findIndex((item) => item.id === entityData.id);

Expand All @@ -77,6 +88,15 @@ export const createEntityApiUtils = <
existingEntity,
);
}
} else if ('pages' in endpointData && Array.isArray(endpointData.pages)) {
const { pageIndex, itemIndex } = findEntityInPages(endpointData.pages, entityData.id);

if (pageIndex > -1 && itemIndex > -1) {
endpointData.pages[pageIndex].data[itemIndex] = mergeEntity(
endpointData.pages[pageIndex].data[itemIndex],
existingEntity,
);
}
} else {
mergeEntity(endpointData as TEntity, existingEntity);
}
Expand Down Expand Up @@ -106,15 +126,35 @@ export const createEntityApiUtils = <
for (const { endpointName, originalArgs } of cachedQueries) {
const action = api.util.updateQueryData(
endpointName as EntityQueryEndpointName,
originalArgs as any,
(endpointData) => {
originalArgs as never,
(data) => {
const endpointData = data as MaybeDrafted<
| TEntity
| TSearchResponse
| (TSearchResponse & {
minPage?: number;
})
| InfiniteData<TSearchResponse, number>
>;

if ('data' in endpointData && Array.isArray(endpointData.data)) {
const existingItemIndex = endpointData.data.findIndex((item) => item.id === id);

if (existingItemIndex > -1) {
endpointData.data.splice(existingItemIndex, 1);
endpointData.pagination.total--;
}
} else if ('pages' in endpointData && Array.isArray(endpointData.pages)) {
const { pageIndex, itemIndex } = findEntityInPages(endpointData.pages, id);

if (pageIndex > -1 && itemIndex > -1) {
endpointData.pages[pageIndex].data.splice(itemIndex, 1);
endpointData.pages.filter((pages) => !!pages.data.length);

for (let i = 0; i < endpointData.pages.length; i++) {
endpointData.pages[i].pagination.total--;
}
}
}
},
);
Expand Down
26 changes: 26 additions & 0 deletions src/utils/find-entity-in-pages.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { Draft } from 'immer';
import { BaseEntity, PaginationResponse } from '../models';

export const findEntityInPages = <
TEntity extends BaseEntity,
TSearchResponse extends PaginationResponse<TEntity> = PaginationResponse<TEntity>,
>(
pages: Array<TSearchResponse> | Draft<Array<TSearchResponse>>,
entityId: unknown,
): { pageIndex: number; itemIndex: number } => {
let itemIndex = -1;

const pageIndex = pages.findIndex((page) => {
const foundItemIndex = page.data.findIndex((item: { id: unknown }) => item.id === entityId);

if (itemIndex !== -1) {
itemIndex = foundItemIndex;

return true;
}

return false;
});

return { itemIndex, pageIndex };
};
1 change: 1 addition & 0 deletions src/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,5 @@ export * from './merge-entity';
export * from './prepare-request-params';
export * from './prepare-server-side-request-headers';
export * from './setup-refetch-listeners';
export * from './find-entity-in-pages';
export * from './store';