diff options
author | eug-vs <eug-vs@keemail.me> | 2021-04-20 11:01:29 +0300 |
---|---|---|
committer | eug-vs <eug-vs@keemail.me> | 2021-04-20 11:01:42 +0300 |
commit | 8168218491ef454576079ad119e5deacf879d383 (patch) | |
tree | 9056f990d1bbc587ef490439395f9950b2445f44 /src/hooks/useAPIClient.ts | |
parent | 50f7d5d888b87f81fd399b677bfd542761091e94 (diff) | |
download | commercel-ui-8168218491ef454576079ad119e5deacf879d383.tar.gz |
refactor: strongly type API Client hooks
Diffstat (limited to 'src/hooks/useAPIClient.ts')
-rw-r--r-- | src/hooks/useAPIClient.ts | 31 |
1 files changed, 11 insertions, 20 deletions
diff --git a/src/hooks/useAPIClient.ts b/src/hooks/useAPIClient.ts index 3035c51..fd3ee19 100644 --- a/src/hooks/useAPIClient.ts +++ b/src/hooks/useAPIClient.ts @@ -1,12 +1,20 @@ -import useSWR, { responseInterface } from 'swr'; +import useSWR, { SWRConfiguration, SWRResponse } from 'swr'; import _ from 'lodash'; import { get } from '../requests'; -type Response<T> = responseInterface<T, Error>; +type Response<T> = SWRResponse<T, Error>; const fetcher = (endpoint: string) => get(endpoint).then(response => response.data); -const hooks: any = {}; + +interface ServiceHooks<T = any> { + useList: (query?: string, options?: SWRConfiguration) => Response<T[]> + useItem: (id: string) => Response<T> +} + +type Hooks = Record<string, ServiceHooks>; + +const hooks: Hooks = {}; const registerServiceHooks = <Item = any>(service: string): void => { if (hooks[service]) return; @@ -30,22 +38,5 @@ const registerServiceHooks = <Item = any>(service: string): void => { hooks[service] = { useItem, useList }; }; -hooks.account = { - useList: () => { - const { data: transfers } = useSWR('/transfers', fetcher); - const dates = _.groupBy(transfers, 'date'); - const dataUnsorted = _.map(dates, (dateTransfers, date) => ({ - _id: dateTransfers[0]._id, // fake: sample id for unique key - date, - amount: _ - .sumBy(dateTransfers, transfer => transfer.amount * (transfer.operation === 'in' ? 1 : -1)) - .toFixed(1), - })); - const data = _.sortBy(dataUnsorted, 'date').reverse(); - return { data }; - }, -}; - - export { registerServiceHooks }; export default hooks; |