Skip to content

Commit

Permalink
♻️(frontend) useAddresses with new api
Browse files Browse the repository at this point in the history
now that we've generated types and api client, we need to use them into
our api hooks
  • Loading branch information
rlecellier committed Mar 6, 2024
1 parent 6b9599a commit e1c5394
Showing 1 changed file with 31 additions and 6 deletions.
37 changes: 31 additions & 6 deletions src/frontend/js/hooks/useAddresses.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
import { defineMessages } from 'react-intl';
import { MutateOptions } from '@tanstack/react-query';
import { useJoanieApi } from 'contexts/JoanieApiContext';
import { Address, AddressCreationPayload, API } from 'types/Joanie';
import { joanieApi } from 'api/joanie/client';
import type { Address } from 'api/joanie/gen';
import { PatchedAddressRequest } from 'api/joanie/gen';
import { ApiResourceInterface, PaginatedResourceQuery } from 'types/Joanie';
import { Maybe } from 'types/utils';
import { HttpError } from 'utils/errors/HttpError';
import { ResourcesQuery, useResource, useResources, UseResourcesProps } from './useResources';

import { useResource, useResources, UseResourcesProps } from './useResources';

const messages = defineMessages({
errorUpdate: {
Expand Down Expand Up @@ -33,15 +37,36 @@ const messages = defineMessages({
},
});

export type AddressesMutateOptions = MutateOptions<Address, HttpError, AddressCreationPayload>;
export type AddressesMutateOptions = MutateOptions<PatchedAddressRequest, HttpError, Address>;

const apiInterface: ApiResourceInterface<Address, PaginatedResourceQuery> = {
get: (resourceQuery?: Maybe<PaginatedResourceQuery>) => {
const { id, ...filters } = resourceQuery || {};
if (id) {
return joanieApi.addresses.addressesRetrieve(id);
}
return joanieApi.addresses.addressesList(filters.page, filters.page_size);
},
create: (data: Address) => {
return joanieApi.addresses.addressesCreate(data);
},
update: (data: PatchedAddressRequest & { id: string }) => {
const { id, ...updateData } = data;
return joanieApi.addresses.addressesPartialUpdate(id, updateData);
},
delete: (id: string) => {
return joanieApi.addresses.addressesDestroy(id);
},
};

/**
* Joanie Api hook to retrieve/create/update/delete addresses
* owned by the authenticated user.
*/
const props: UseResourcesProps<Address, ResourcesQuery, API['user']['addresses']> = {
// FIXME: now that we've both Address and PatchedAddress, UseResourcesProps cannot be build from a unique input/output type.
const props: UseResourcesProps<Address, PaginatedResourceQuery, typeof apiInterface> = {
queryKey: ['addresses'],
apiInterface: () => useJoanieApi().user.addresses,
apiInterface: () => apiInterface,
omniscient: true,
session: true,
messages,
Expand Down

0 comments on commit e1c5394

Please sign in to comment.