diff options
Diffstat (limited to 'src/hooks/useAPIClient.ts')
-rw-r--r-- | src/hooks/useAPIClient.ts | 57 |
1 files changed, 26 insertions, 31 deletions
diff --git a/src/hooks/useAPIClient.ts b/src/hooks/useAPIClient.ts index eb427f1..8f3a077 100644 --- a/src/hooks/useAPIClient.ts +++ b/src/hooks/useAPIClient.ts @@ -1,11 +1,32 @@ import useSWR, { responseInterface } from 'swr'; import _ from 'lodash'; import { get } from '../requests'; +import services from '../services'; type Response<T> = responseInterface<T, Error>; const fetcher = (endpoint: string) => get(endpoint).then(response => response.data); +const createServiceHooks = <Item = any>(service: string) => { + const useList = (options = {}): Response<Item[]> => { + return useSWR(`/${service}`, fetcher, options); + }; + + const useItem = (_id: string): Response<Item> => { + const { data: preloadedItems } = useList({ revalidateOnMount: false }); + const result = useSWR(_id && `/${service}/${_id}`, fetcher); + if (!result.data && result.isValidating) { + // If we are waiting for the first result, check if we can maybe + // get the data from already cached list for the time-being + const item = _.find(preloadedItems, { _id }); + return { ...result, data: item } as Response<Item>; + } + return result; + }; + + return { useItem, useList }; +}; + // Products export interface Product { _id: string; @@ -18,23 +39,6 @@ export interface Product { updatedAt: string; } -export const useProducts = (options = {}): Response<Product[]> => { - return useSWR('/products', fetcher, options); -}; - -export const useProduct = (_id: string): Response<Product> => { - const { data: preloadedProducts } = useProducts({ revalidateOnMount: false }); - const result = useSWR(_id && `/products/${_id}`, fetcher); - if (!result.data && result.isValidating) { - // If we are waiting for the first result, check if we can maybe - // get the data from already cached list for the time-being - const product = _.find(preloadedProducts, { _id }); - return { ...result, data: product }; - } - return result; -}; - - // Contractors export interface Contractor { _id: string; @@ -45,18 +49,9 @@ export interface Contractor { debt: number; } -export const useContractors = (options = {}): Response<Product[]> => { - return useSWR('/contractors', fetcher, options); -}; +const hooks = services.reduce((acc, { route }) => { + return _.set(acc, route, createServiceHooks(route)); +}, {}); -export const useContractor = (_id: string): Response<Product> => { - const { data: preloadedContractors } = useContractors({ revalidateOnMount: false }); - const result = useSWR(_id && `/contractors/${_id}`, fetcher); - if (!result.data && result.isValidating) { - // If we are waiting for the first result, check if we can maybe - // get the data from already cached list for the time-being - const contractor = _.find(preloadedContractors, { _id }); - return { ...result, data: contractor }; - } - return result; -}; + +export default hooks as any; |