2023-03-24 00:22:26 +00:00
|
|
|
import { useApi } from 'soapbox/hooks';
|
|
|
|
|
2023-03-22 20:31:58 +00:00
|
|
|
import { useCreateEntity } from './useCreateEntity';
|
2023-03-22 19:05:24 +00:00
|
|
|
import { useDeleteEntity } from './useDeleteEntity';
|
2023-03-22 21:06:10 +00:00
|
|
|
import { parseEntitiesPath } from './utils';
|
2023-03-14 19:24:11 +00:00
|
|
|
|
|
|
|
import type { Entity } from '../types';
|
2023-03-22 21:06:10 +00:00
|
|
|
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
|
|
|
|
}
|
|
|
|
|
2023-03-23 19:52:38 +00:00
|
|
|
function useEntityActions<TEntity extends Entity = Entity, Data = any>(
|
2023-03-22 21:06:10 +00:00
|
|
|
expandedPath: ExpandedEntitiesPath,
|
2023-03-14 19:24:11 +00:00
|
|
|
endpoints: EntityActionEndpoints,
|
|
|
|
opts: UseEntityActionsOpts<TEntity> = {},
|
|
|
|
) {
|
2023-03-24 00:22:26 +00:00
|
|
|
const api = useApi();
|
2023-03-22 21:12:05 +00:00
|
|
|
const { entityType, path } = parseEntitiesPath(expandedPath);
|
2023-03-23 19:52:38 +00:00
|
|
|
|
2023-03-23 20:30:45 +00:00
|
|
|
const { deleteEntity, isLoading: deleteLoading } =
|
2023-03-24 00:22:26 +00:00
|
|
|
useDeleteEntity(entityType, (entityId) => api.delete(endpoints.delete!.replaceAll(':id', entityId)));
|
2023-03-14 19:24:11 +00:00
|
|
|
|
2023-03-23 20:30:45 +00:00
|
|
|
const { createEntity, isLoading: createLoading } =
|
2023-03-24 00:22:26 +00:00
|
|
|
useCreateEntity<TEntity, Data>(path, (data) => api.post(endpoints.post!, data), opts);
|
2023-03-23 20:05:34 +00:00
|
|
|
|
2023-03-14 19:24:11 +00:00
|
|
|
return {
|
2023-03-22 20:31:58 +00:00
|
|
|
createEntity,
|
|
|
|
deleteEntity,
|
2023-03-23 20:30:45 +00:00
|
|
|
isLoading: createLoading || deleteLoading,
|
2023-03-14 19:24:11 +00:00
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
export { useEntityActions };
|