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

45 lines
1.4 KiB
TypeScript
Raw Normal View History

import { useApi } from 'soapbox/hooks';
import { useCreateEntity } from './useCreateEntity';
import { useDeleteEntity } from './useDeleteEntity';
import { parseEntitiesPath } from './utils';
2023-03-14 12:24:11 -07:00
import type { Entity } from '../types';
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 {
delete?: string
2023-03-23 12:20:19 -07:00
patch?: string
post?: string
2023-03-14 12:24:11 -07:00
}
function useEntityActions<TEntity extends Entity = Entity, Data = any>(
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);
const { deleteEntity, isSubmitting: deleteSubmitting } =
useDeleteEntity(entityType, (entityId) => api.delete(endpoints.delete!.replaceAll(':id', entityId)));
2023-03-14 12:24:11 -07:00
const { createEntity, isSubmitting: createSubmitting } =
useCreateEntity<TEntity, Data>(path, (data) => api.post(endpoints.post!, data), opts);
2023-04-14 12:15:34 -07:00
const { createEntity: updateEntity, isSubmitting: updateSubmitting } =
useCreateEntity<TEntity, Data>(path, (data) => api.patch(endpoints.patch!, data), opts);
2023-03-14 12:24:11 -07:00
return {
createEntity,
deleteEntity,
2023-04-14 12:15:34 -07:00
updateEntity,
isSubmitting: createSubmitting || deleteSubmitting || updateSubmitting,
2023-03-14 12:24:11 -07:00
};
}
export { useEntityActions };