2023-03-20 10:27:22 -07:00
|
|
|
import { useState } from 'react';
|
2023-03-14 12:24:11 -07:00
|
|
|
|
2023-03-22 13:31:58 -07:00
|
|
|
import { useApi } from 'soapbox/hooks';
|
2023-03-22 12:05:24 -07:00
|
|
|
|
2023-03-22 13:31:58 -07:00
|
|
|
import { useCreateEntity } from './useCreateEntity';
|
2023-03-22 12:05:24 -07:00
|
|
|
import { useDeleteEntity } from './useDeleteEntity';
|
2023-03-22 14:06:10 -07:00
|
|
|
import { parseEntitiesPath } from './utils';
|
2023-03-14 12:24:11 -07:00
|
|
|
|
|
|
|
import type { Entity } from '../types';
|
2023-03-22 14:06:10 -07:00
|
|
|
import type { EntitySchema, ExpandedEntitiesPath } from './types';
|
2023-03-14 12:24:11 -07:00
|
|
|
|
|
|
|
interface UseEntityActionsOpts<TEntity extends Entity = Entity> {
|
|
|
|
schema?: EntitySchema<TEntity>
|
|
|
|
}
|
|
|
|
|
|
|
|
interface EntityActionEndpoints {
|
|
|
|
post?: string
|
|
|
|
delete?: string
|
|
|
|
}
|
|
|
|
|
2023-03-23 12:52:38 -07:00
|
|
|
function useEntityActions<TEntity extends Entity = Entity, Data = any>(
|
2023-03-22 14:06:10 -07:00
|
|
|
expandedPath: ExpandedEntitiesPath,
|
2023-03-14 12:24:11 -07:00
|
|
|
endpoints: EntityActionEndpoints,
|
|
|
|
opts: UseEntityActionsOpts<TEntity> = {},
|
|
|
|
) {
|
|
|
|
const api = useApi();
|
2023-03-22 14:12:05 -07:00
|
|
|
const { entityType, path } = parseEntitiesPath(expandedPath);
|
2023-03-22 12:05:24 -07:00
|
|
|
|
2023-03-20 10:27:22 -07:00
|
|
|
const [isLoading, setIsLoading] = useState<boolean>(false);
|
|
|
|
|
2023-03-22 12:05:24 -07:00
|
|
|
const deleteEntity = useDeleteEntity(entityType, (entityId) => {
|
|
|
|
if (!endpoints.delete) return Promise.reject(endpoints);
|
2023-03-23 08:23:06 -07:00
|
|
|
return api.delete(endpoints.delete.replace(':id', entityId))
|
|
|
|
.finally(() => setIsLoading(false));
|
2023-03-22 12:05:24 -07:00
|
|
|
});
|
2023-03-14 12:24:11 -07:00
|
|
|
|
2023-03-23 12:52:38 -07:00
|
|
|
const create = useCreateEntity<TEntity, Data>(path, { method: 'post', url: endpoints.post }, opts);
|
|
|
|
|
|
|
|
const createEntity: typeof create = async (...args) => {
|
|
|
|
await create(...args);
|
|
|
|
setIsLoading(false);
|
|
|
|
};
|
2023-03-14 12:24:11 -07:00
|
|
|
|
|
|
|
return {
|
2023-03-22 13:31:58 -07:00
|
|
|
createEntity,
|
|
|
|
deleteEntity,
|
2023-03-20 10:27:22 -07:00
|
|
|
isLoading,
|
2023-03-14 12:24:11 -07:00
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
export { useEntityActions };
|