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

50 lines
1.4 KiB
TypeScript
Raw Normal View History

2023-03-20 10:27:22 -07:00
import { useState } from 'react';
2023-03-14 12:24:11 -07:00
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 {
post?: string
delete?: string
}
function useEntityActions<TEntity extends Entity = Entity, Params = 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);
2023-03-20 10:27:22 -07:00
const [isLoading, setIsLoading] = useState<boolean>(false);
const deleteEntity = useDeleteEntity(entityType, (entityId) => {
if (!endpoints.delete) return Promise.reject(endpoints);
return api.delete(endpoints.delete.replace(':id', entityId))
.finally(() => setIsLoading(false));
});
2023-03-14 12:24:11 -07:00
const createEntity = useCreateEntity(path, (params: Params) => {
2023-03-14 12:24:11 -07:00
if (!endpoints.post) return Promise.reject(endpoints);
return api.post(endpoints.post, params)
.finally(() => setIsLoading(false));
}, opts);
2023-03-14 12:24:11 -07:00
return {
createEntity,
deleteEntity,
2023-03-20 10:27:22 -07:00
isLoading,
2023-03-14 12:24:11 -07:00
};
}
export { useEntityActions };