Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: useOwnItems hook to receive page number #426

Closed
wants to merge 20 commits into from
Closed
Show file tree
Hide file tree
Changes from 18 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
26 changes: 21 additions & 5 deletions src/api/item.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
import { DiscriminatedItem, Item, ResultOf, UUID } from '@graasp/sdk';

import { DEFAULT_THUMBNAIL_SIZE } from '../config/constants';
import { QueryClientConfig } from '../types';
import { PaginationArgs, QueryClientConfig } from '../types';
import { getParentsIdsFromPath } from '../utils/item';
import configureAxios, { verifyAuthentication } from './axios';
import {
GET_OWN_ITEMS_ROUTE,
GET_RECYCLED_ITEMS_DATA_ROUTE,
SHARED_ITEM_WITH_ROUTE,
buildCopyItemsRoute,
Expand All @@ -18,6 +17,7 @@ import {
buildGetItemParents,
buildGetItemRoute,
buildGetItemsRoute,
buildGetOwnItemsRoute,
buildMoveItemsRoute,
buildPostItemRoute,
buildRecycleItemsRoute,
Expand All @@ -35,10 +35,26 @@ export const getItems = async (
): Promise<ResultOf<Item>> =>
axios.get(`${API_HOST}/${buildGetItemsRoute(ids)}`).then(({ data }) => data);

export const getOwnItems = async ({ API_HOST }: QueryClientConfig) =>
verifyAuthentication(() =>
axios.get(`${API_HOST}/${GET_OWN_ITEMS_ROUTE}`).then(({ data }) => data),
export const getOwnItems = async (
{ API_HOST }: QueryClientConfig,
args: PaginationArgs,
searchArgs?: {
name: string;
},
) => {
const { page = 1, limit } = args;
return verifyAuthentication(() =>
axios
.get(
`${API_HOST}/${buildGetOwnItemsRoute({
page,
name: searchArgs?.name,
limit,
})}`,
)
.then(({ data }) => data),
);
};

export type PostItemPayloadType = Partial<DiscriminatedItem> &
Pick<DiscriminatedItem, 'type' | 'name'> & {
Expand Down
16 changes: 15 additions & 1 deletion src/api/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,14 @@ import { DiscriminatedItem, ItemTag, ItemTagType, UUID } from '@graasp/sdk';
import qs from 'qs';

import { DEFAULT_THUMBNAIL_SIZE } from '../config/constants';
import { OwnItemsQuery } from '../types';
import { AggregateActionsArgs } from '../utils/action';

export const APPS_ROUTE = 'app-items';
export const ITEMS_ROUTE = 'items';
export const ITEM_MEMBERSHIPS_ROUTE = 'item-memberships';
export const MEMBERS_ROUTE = `members`;
export const SUBSCRIPTION_ROUTE = 'subscriptions';
export const GET_OWN_ITEMS_ROUTE = `${ITEMS_ROUTE}/own`;
export const INVITATIONS_ROUTE = `invitations`;
export const GET_RECYCLED_ITEMS_DATA_ROUTE = `${ITEMS_ROUTE}/recycled`;
export const GET_FAVORITE_ITEMS_ROUTE = `${ITEMS_ROUTE}/favorite`;
Expand All @@ -20,6 +20,19 @@ export const ETHERPAD_ROUTE = `${ITEMS_ROUTE}/etherpad`;
export const COLLECTIONS_ROUTE = `collections`;
export const buildAppListRoute = `${APPS_ROUTE}/list`;

export const GET_OWN_ITEMS_ROUTE = `${ITEMS_ROUTE}/own`;
export const buildGetOwnItemsRoute = ({
page = 1,
name,
limit,
}: OwnItemsQuery) => {
const url = `${GET_OWN_ITEMS_ROUTE}${qs.stringify(
{ page, name, limit },
{ addQueryPrefix: true },
)}`;
return url;
};

export const buildPostItemRoute = (parentId?: UUID) => {
let url = ITEMS_ROUTE;
if (parentId) {
Expand Down Expand Up @@ -486,4 +499,5 @@ export const API_ROUTES = {
SIGN_OUT_ROUTE,
SIGN_UP_ROUTE,
VALIDATION_ROUTE,
buildGetOwnItemsRoute,
};
8 changes: 8 additions & 0 deletions src/config/keys.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,19 @@
import { Category, UUID } from '@graasp/sdk';

import { PaginationArgs } from '../types';
import { AggregateActionsArgs } from '../utils/action';
import { hashItemsIds } from '../utils/item';
import { DEFAULT_THUMBNAIL_SIZE } from './constants';

export const APPS_KEY = 'apps';
export const ITEMS_KEY = 'items';
export const OWN_ITEMS_KEY = [ITEMS_KEY, 'own'];
export const buildOwnItemsKey = (
args: PaginationArgs,
searchArgs?: {
name: string;
},
) => [ITEMS_KEY, 'own', args.page, args.limit, searchArgs?.name];
Copy link
Contributor

Choose a reason for hiding this comment

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

Suggested change
) => [ITEMS_KEY, 'own', args.page, args.limit, searchArgs?.name];
) => [ITEMS_KEY, 'own', { page: args.page, limit: args.limit }, searchArgs];

export const ETHERPADS_KEY = 'etherpads';
export const SUBSCRIPTION_KEY = 'subscriptions';

Expand Down Expand Up @@ -290,5 +297,6 @@ export const DATA_KEYS = {
buildPlanKey,
buildPublishedItemsKey,
buildEtherpadKey,
buildOwnItemsKey,
buildSearchPublishedItemsKey,
};
34 changes: 18 additions & 16 deletions src/hooks/item.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,14 +28,14 @@ import {
splitEndpointByIds,
} from '../../test/utils';
import {
GET_OWN_ITEMS_ROUTE,
SHARED_ITEM_WITH_ROUTE,
buildDownloadFilesRoute,
buildDownloadItemThumbnailRoute,
buildGetChildrenRoute,
buildGetItemParents,
buildGetItemRoute,
buildGetItemsRoute,
buildGetOwnItemsRoute,
} from '../api/routes';
import {
OWN_ITEMS_KEY,
Expand All @@ -46,6 +46,7 @@ import {
buildItemParentsKey,
buildItemThumbnailKey,
buildItemsKey,
buildOwnItemsKey,
} from '../config/keys';

const { hooks, wrapper, queryClient } = setUpTest();
Expand All @@ -58,25 +59,26 @@ describe('Items Hooks', () => {
});

describe('useOwnItems', () => {
const route = `/${GET_OWN_ITEMS_ROUTE}`;
const hook = () => hooks.useOwnItems();
const route = `/${buildGetOwnItemsRoute({ page: 1, limit: 10 })}`;
const hook = () => hooks.useOwnItems({ page: 1, limit: 10 });

it(`Receive own items`, async () => {
const response = ITEMS;
const response = { data: ITEMS };
const endpoints = [{ route, response }];
const { data } = await mockHook({ endpoints, hook, wrapper });

expect(Immutable.is(data, response)).toBeTruthy();

// eslint-disable-next-line @typescript-eslint/no-explicit-any
const { data }: { data: any } = await mockHook({
endpoints,
hook,
wrapper,
});
// verify cache keys
expect(
Immutable.is(queryClient.getQueryData(OWN_ITEMS_KEY), response),
).toBeTruthy();
for (const item of response) {
expect(
Immutable.is(queryClient.getQueryData(buildItemKey(item.id)), item),
).toBeTruthy();
}
const res: { data: List<ItemRecord> } | undefined =
await queryClient.getQueryData(
buildOwnItemsKey({ page: 1, limit: 10 }),
);

expect(Immutable.is(res?.data, response.data)).toBeTruthy();
expect(Immutable.is(data?.data, response.data)).toBeTruthy();
});

it(`Unauthorized`, async () => {
Expand Down
26 changes: 16 additions & 10 deletions src/hooks/item.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@ import {
} from '../config/constants';
import { UndefinedArgument } from '../config/errors';
import {
OWN_ITEMS_KEY,
RECYCLED_ITEMS_DATA_KEY,
SHARED_ITEMS_KEY,
buildEtherpadKey,
Expand All @@ -43,9 +42,10 @@ import {
buildItemParentsKey,
buildItemThumbnailKey,
buildItemsKey,
buildOwnItemsKey,
} from '../config/keys';
import { getOwnItemsRoutine } from '../routines';
import { QueryClientConfig } from '../types';
import { Paginated, PaginationArgs, QueryClientConfig } from '../types';
import { isPaginatedChildrenDataEqual, paginate } from '../utils/util';
import { configureWsItemHooks } from '../ws';
import { WebsocketClient } from '../ws/ws-client';
Expand All @@ -63,21 +63,27 @@ export default (
: undefined;

return {
useOwnItems: (options?: { getUpdates?: boolean }) => {
useOwnItems: (
args: PaginationArgs,
searchArgs?: {
name: string;
},
options?: { getUpdates?: boolean },
) => {
const queryClient = useQueryClient();
const getUpdates = options?.getUpdates ?? enableWebsocket;

const { data: currentMember } = useCurrentMember();
itemWsHooks?.useOwnItemsUpdates(getUpdates ? currentMember?.id : null);

return useQuery({
queryKey: OWN_ITEMS_KEY,
queryFn: (): Promise<List<ItemRecord>> =>
Api.getOwnItems(queryConfig).then((data) => convertJs(data)),
onSuccess: async (items: List<ItemRecord>) => {
// save items in their own key
// eslint-disable-next-line no-unused-expressions
items?.forEach(async (item) => {
queryKey: buildOwnItemsKey(args, searchArgs),
queryFn: (): Promise<Paginated<ItemRecord>> =>
Api.getOwnItems(queryConfig, args, searchArgs).then((data) =>
convertJs(data),
),
onSuccess: async ({ data }: Paginated<ItemRecord>) => {
data.forEach(async (item) => {
const { id } = item;
queryClient.setQueryData(buildItemKey(id), item);
});
Expand Down
7 changes: 5 additions & 2 deletions src/hooks/membership.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,8 +83,11 @@ export default (
throw new UndefinedArgument();
}

return splitRequestByIds(ids, MAX_TARGETS_FOR_READ_REQUEST, (chunk) =>
Api.getMembershipsForItems(chunk, queryConfig),
return splitRequestByIds(
ids,
MAX_TARGETS_FOR_READ_REQUEST,
(chunk) => Api.getMembershipsForItems(chunk, queryConfig),
true,
);
},
onSuccess: async (memberships) => {
Expand Down
17 changes: 17 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { AxiosError } from 'axios';
import { List } from 'immutable';
import { QueryObserverOptions } from 'react-query';

import { isDataEqual } from './utils/util';
Expand Down Expand Up @@ -35,3 +36,19 @@ export type QueryClientConfig = {
isDataEqual?: typeof isDataEqual;
};
};

export type OwnItemsQuery = {
page?: number;
name?: string;
limit?: number;
};
Comment on lines +40 to +44
Copy link
Contributor

Choose a reason for hiding this comment

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

Not used anymore?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

indeed used, I think u're talking about all?
@pyphilia


export type PaginationArgs = {
page?: number;
limit?: number;
};

export type Paginated<T> = {
totalCount: number;
data: List<T>;
};