82 lines
2.7 KiB
TypeScript
82 lines
2.7 KiB
TypeScript
import { useApplication } from "../../../presentation/providers/application-provider.js";
|
|
import {
|
|
useApplicationMutation,
|
|
useApplicationQuery,
|
|
} from "../../../presentation/adapters/query/application-query.js";
|
|
import { useRouteInput } from "../../../presentation/routes/app-router.js";
|
|
import type { ReferenceResourceView } from "../contracts/reference-mapper.js";
|
|
import {
|
|
REFERENCE_FEATURE_ID,
|
|
referenceQueryKeys,
|
|
} from "../contracts/reference-feature-contract.js";
|
|
import type {
|
|
ReferenceFeatureInput,
|
|
ReferenceListFilters,
|
|
} from "../application/reference-feature-api.js";
|
|
|
|
export function useReferenceFeatureInput(): ReferenceFeatureInput {
|
|
const candidate = useApplication().features.get(REFERENCE_FEATURE_ID);
|
|
if (
|
|
!candidate ||
|
|
typeof candidate !== "object" ||
|
|
typeof (candidate as ReferenceFeatureInput).listResources !== "function" ||
|
|
typeof (candidate as ReferenceFeatureInput).createResource !== "function" ||
|
|
typeof (candidate as ReferenceFeatureInput).getResource !== "function"
|
|
) {
|
|
throw new Error("Reference feature application input is invalid");
|
|
}
|
|
return candidate as ReferenceFeatureInput;
|
|
}
|
|
|
|
export function useReferenceDetail(resourceId: string) {
|
|
const input = useReferenceFeatureInput();
|
|
const query = useApplicationQuery({
|
|
queryKey: referenceQueryKeys.detail(resourceId),
|
|
execute: ({ signal }) => input.getResource(resourceId, { signal }),
|
|
});
|
|
return Object.freeze({ query });
|
|
}
|
|
|
|
export function useReferenceCreate() {
|
|
const input = useReferenceFeatureInput();
|
|
return useApplicationMutation({
|
|
execute: input.createResource,
|
|
invalidate: [referenceQueryKeys.all()],
|
|
currentData: true,
|
|
});
|
|
}
|
|
|
|
export function useReferenceFeature() {
|
|
const input = useReferenceFeatureInput();
|
|
const routeInput = useRouteInput();
|
|
const filters = routeInput.search as ReferenceListFilters;
|
|
const queryKey = referenceQueryKeys.list(filters);
|
|
const query = useApplicationQuery({
|
|
queryKey,
|
|
execute: ({ signal }) => input.listResources(filters, { signal }),
|
|
});
|
|
const mutation = useApplicationMutation({
|
|
execute: input.createResource,
|
|
invalidate: [referenceQueryKeys.all()],
|
|
currentData: true,
|
|
optimistic: {
|
|
queryKey,
|
|
update(previous, command: Readonly<{ name: string }>) {
|
|
const current = Array.isArray(previous)
|
|
? (previous as readonly ReferenceResourceView[])
|
|
: [];
|
|
return [
|
|
...current,
|
|
{
|
|
resourceId: `optimistic:${command.name}`,
|
|
title: command.name,
|
|
createdAt: null,
|
|
optimistic: true,
|
|
},
|
|
];
|
|
},
|
|
},
|
|
});
|
|
return Object.freeze({ filters, query, mutation });
|
|
}
|