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

44 lines
1.2 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 {
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();
const path = parseEntitiesPath(expandedPath);
const [entityType] = path;
const deleteEntity = useDeleteEntity(entityType, (entityId) => {
if (!endpoints.delete) return Promise.reject(endpoints);
return api.delete(endpoints.delete.replace(':id', entityId));
});
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);
}, opts);
2023-03-14 12:24:11 -07:00
return {
createEntity,
deleteEntity,
2023-03-14 12:24:11 -07:00
};
}
export { useEntityActions };