57 lines
1.8 KiB
TypeScript
57 lines
1.8 KiB
TypeScript
import { useDataSource } from "@erp/core/hooks";
|
|
import { ValidationErrorCollection } from "@repo/rdx-ddd";
|
|
import { type DefaultError, useMutation, useQueryClient } from "@tanstack/react-query";
|
|
|
|
import { UpdateCustomerByIdRequestSchema } from "../../../common";
|
|
import { GetCustomerByIdAdapter } from "../adapters";
|
|
import {
|
|
type UpdateCustomerByIdParams,
|
|
type UpdateCustomerByIdResult,
|
|
updateCustomerById,
|
|
} from "../api";
|
|
import type { Customer } from "../entities";
|
|
|
|
import {
|
|
invalidateCustomerListQueries,
|
|
syncUpdatedCustomerCaches,
|
|
} from "./customer-cache-strategy";
|
|
import { CUSTOMER_UPDATE_KEY } from "./keys";
|
|
import { toValidationErrors } from "./to-validation-errors";
|
|
|
|
type UpdateCustomerContext = {};
|
|
|
|
export const useCustomerUpdateMutation = () => {
|
|
const queryClient = useQueryClient();
|
|
const dataSource = useDataSource();
|
|
const schema = UpdateCustomerByIdRequestSchema;
|
|
|
|
return useMutation<Customer, DefaultError, UpdateCustomerByIdParams, UpdateCustomerContext>({
|
|
mutationKey: CUSTOMER_UPDATE_KEY,
|
|
|
|
mutationFn: async (payload) => {
|
|
const { id: customerId, data } = payload;
|
|
if (!customerId) {
|
|
throw new Error("customerId is required");
|
|
}
|
|
|
|
const result = schema.safeParse(data);
|
|
if (!result.success) {
|
|
throw new ValidationErrorCollection("Validation failed", toValidationErrors(result.error));
|
|
}
|
|
|
|
const dto: UpdateCustomerByIdResult = await updateCustomerById(
|
|
dataSource,
|
|
payload as UpdateCustomerByIdParams
|
|
);
|
|
return GetCustomerByIdAdapter.fromDTO(dto);
|
|
},
|
|
|
|
onSuccess: (updatedCustomer) => {
|
|
syncUpdatedCustomerCaches(queryClient, updatedCustomer);
|
|
},
|
|
onSettled: async () => {
|
|
await invalidateCustomerListQueries(queryClient);
|
|
},
|
|
});
|
|
};
|