soapbox/app/soapbox/entity-store/hooks/useEntityActions.ts

40 wiersze
1.2 KiB
TypeScript
Czysty Zwykły widok Historia

import { useApi } from 'soapbox/hooks';
import { useCreateEntity } from './useCreateEntity';
import { useDeleteEntity } from './useDeleteEntity';
import { parseEntitiesPath } from './utils';
2023-03-14 19:24:11 +00:00
import type { Entity } from '../types';
import type { EntitySchema, ExpandedEntitiesPath } from './types';
2023-03-14 19:24:11 +00:00
interface UseEntityActionsOpts<TEntity extends Entity = Entity> {
schema?: EntitySchema<TEntity>
}
interface EntityActionEndpoints {
post?: string
delete?: string
}
function useEntityActions<TEntity extends Entity = Entity, Data = any>(
expandedPath: ExpandedEntitiesPath,
2023-03-14 19:24:11 +00:00
endpoints: EntityActionEndpoints,
opts: UseEntityActionsOpts<TEntity> = {},
) {
const api = useApi();
2023-03-22 21:12:05 +00:00
const { entityType, path } = parseEntitiesPath(expandedPath);
const { deleteEntity, isLoading: deleteLoading } =
useDeleteEntity(entityType, (entityId) => api.delete(endpoints.delete!.replaceAll(':id', entityId)));
2023-03-14 19:24:11 +00:00
const { createEntity, isLoading: createLoading } =
useCreateEntity<TEntity, Data>(path, (data) => api.post(endpoints.post!, data), opts);
2023-03-14 19:24:11 +00:00
return {
createEntity,
deleteEntity,
isLoading: createLoading || deleteLoading,
2023-03-14 19:24:11 +00:00
};
}
export { useEntityActions };