2025-09-16 17:29:37 +00:00
|
|
|
import { useDataSource } from "@erp/core/hooks";
|
2025-09-24 10:34:04 +00:00
|
|
|
import { DefaultError, type QueryKey, useQuery } from "@tanstack/react-query";
|
|
|
|
|
import { CustomerData } from "../schemas";
|
2025-09-16 17:29:37 +00:00
|
|
|
|
|
|
|
|
export const CUSTOMER_QUERY_KEY = (id: string): QueryKey => ["customer", id] as const;
|
|
|
|
|
|
2025-09-24 10:34:04 +00:00
|
|
|
type CustomerQueryOptions = {
|
2025-09-16 17:29:37 +00:00
|
|
|
enabled?: boolean;
|
|
|
|
|
};
|
|
|
|
|
|
2025-09-24 10:34:04 +00:00
|
|
|
export function useCustomerQuery(customerId?: string, options?: CustomerQueryOptions) {
|
2025-09-16 17:29:37 +00:00
|
|
|
const dataSource = useDataSource();
|
|
|
|
|
const enabled = (options?.enabled ?? true) && !!customerId;
|
|
|
|
|
|
2025-09-24 10:34:04 +00:00
|
|
|
const queryResult = useQuery<CustomerData, DefaultError>({
|
2025-09-16 17:29:37 +00:00
|
|
|
queryKey: CUSTOMER_QUERY_KEY(customerId ?? "unknown"),
|
|
|
|
|
queryFn: async (context) => {
|
|
|
|
|
const { signal } = context;
|
2025-09-24 10:34:04 +00:00
|
|
|
if (!customerId) {
|
|
|
|
|
if (!customerId) throw new Error("customerId is required");
|
|
|
|
|
}
|
|
|
|
|
const customer = await dataSource.getOne<CustomerData>("customers", customerId, {
|
|
|
|
|
signal,
|
|
|
|
|
});
|
|
|
|
|
return customer;
|
2025-09-16 17:29:37 +00:00
|
|
|
},
|
2025-09-24 10:34:04 +00:00
|
|
|
enabled,
|
2025-09-16 17:29:37 +00:00
|
|
|
});
|
2025-09-24 10:34:04 +00:00
|
|
|
|
|
|
|
|
return queryResult;
|
2025-09-16 17:29:37 +00:00
|
|
|
}
|
2025-09-24 10:34:04 +00:00
|
|
|
|
|
|
|
|
/*
|
|
|
|
|
export function useQuery<
|
|
|
|
|
TQueryFnData = unknown,
|
|
|
|
|
TError = unknown,
|
|
|
|
|
TData = TQueryFnData,
|
|
|
|
|
TQueryKey extends QueryKey = QueryKey
|
|
|
|
|
>
|
|
|
|
|
|
|
|
|
|
TQueryFnData: the type returned from the queryFn.
|
|
|
|
|
TError: the type of Errors to expect from the queryFn.
|
|
|
|
|
TData: the type our data property will eventually have.
|
|
|
|
|
Only relevant if you use the select option,
|
|
|
|
|
because then the data property can be different
|
|
|
|
|
from what the queryFn returns.
|
|
|
|
|
Otherwise, it will default to whatever the queryFn returns.
|
|
|
|
|
TQueryKey: the type of our queryKey, only relevant
|
|
|
|
|
if you use the queryKey that is passed to your queryFn.
|
|
|
|
|
|
|
|
|
|
*/
|