41 lines
1.2 KiB
TypeScript
41 lines
1.2 KiB
TypeScript
|
|
import { useDataSource } from "@erp/core/hooks";
|
||
|
|
import { GetCustomerByIdResponseDTO } from "@erp/customer-invoices/common";
|
||
|
|
import { type QueryKey, type UseQueryOptions, useQuery } from "@tanstack/react-query";
|
||
|
|
|
||
|
|
export const CUSTOMER_QUERY_KEY = (id: string): QueryKey => ["customer", id] as const;
|
||
|
|
|
||
|
|
type Options = Omit<
|
||
|
|
UseQueryOptions<
|
||
|
|
GetCustomerByIdResponseDTO,
|
||
|
|
Error,
|
||
|
|
GetCustomerByIdResponseDTO,
|
||
|
|
ReturnType<typeof CUSTOMER_QUERY_KEY>
|
||
|
|
>,
|
||
|
|
"queryKey" | "queryFn" | "enabled"
|
||
|
|
> & {
|
||
|
|
enabled?: boolean;
|
||
|
|
};
|
||
|
|
|
||
|
|
export function useCustomerQuery(customerId?: string, options?: Options) {
|
||
|
|
const dataSource = useDataSource();
|
||
|
|
const enabled = (options?.enabled ?? true) && !!customerId;
|
||
|
|
|
||
|
|
return useQuery<
|
||
|
|
GetCustomerByIdResponseDTO,
|
||
|
|
Error,
|
||
|
|
GetCustomerByIdResponseDTO,
|
||
|
|
ReturnType<typeof CUSTOMER_QUERY_KEY>
|
||
|
|
>({
|
||
|
|
queryKey: CUSTOMER_QUERY_KEY(customerId ?? "unknown"),
|
||
|
|
enabled,
|
||
|
|
queryFn: async (context) => {
|
||
|
|
if (!customerId) throw new Error("customerId is required");
|
||
|
|
|
||
|
|
const { signal } = context;
|
||
|
|
const customer = await dataSource.getOne("customers", customerId);
|
||
|
|
return customer as GetCustomerByIdResponseDTO;
|
||
|
|
},
|
||
|
|
...options,
|
||
|
|
});
|
||
|
|
}
|