2023-03-23 13:30:45 -07:00
|
|
|
import { useState } from 'react';
|
2023-03-22 13:31:58 -07:00
|
|
|
import { z } from 'zod';
|
|
|
|
|
2023-03-23 12:52:38 -07:00
|
|
|
import { useApi, useAppDispatch } from 'soapbox/hooks';
|
2023-03-22 13:31:58 -07:00
|
|
|
|
|
|
|
import { importEntities } from '../actions';
|
|
|
|
|
2023-03-23 12:52:38 -07:00
|
|
|
import { parseEntitiesPath, toAxiosRequest } from './utils';
|
2023-03-22 14:06:10 -07:00
|
|
|
|
2023-03-22 13:31:58 -07:00
|
|
|
import type { Entity } from '../types';
|
2023-03-23 12:52:38 -07:00
|
|
|
import type { EntityRequest, EntitySchema, ExpandedEntitiesPath } from './types';
|
2023-03-22 13:31:58 -07:00
|
|
|
|
|
|
|
interface UseCreateEntityOpts<TEntity extends Entity = Entity> {
|
|
|
|
schema?: EntitySchema<TEntity>
|
|
|
|
}
|
|
|
|
|
2023-03-23 13:05:34 -07:00
|
|
|
interface CreateEntityCallbacks<TEntity extends Entity = Entity, Error = unknown> {
|
2023-03-22 13:31:58 -07:00
|
|
|
onSuccess?(entity: TEntity): void
|
|
|
|
onError?(error: Error): void
|
|
|
|
}
|
|
|
|
|
2023-03-23 12:52:38 -07:00
|
|
|
function useCreateEntity<TEntity extends Entity = Entity, Data = any>(
|
2023-03-22 14:06:10 -07:00
|
|
|
expandedPath: ExpandedEntitiesPath,
|
2023-03-23 12:52:38 -07:00
|
|
|
request: EntityRequest,
|
2023-03-22 13:31:58 -07:00
|
|
|
opts: UseCreateEntityOpts<TEntity> = {},
|
|
|
|
) {
|
2023-03-23 12:52:38 -07:00
|
|
|
const api = useApi();
|
2023-03-22 13:31:58 -07:00
|
|
|
const dispatch = useAppDispatch();
|
2023-03-23 13:30:45 -07:00
|
|
|
const [isLoading, setIsLoading] = useState<boolean>(false);
|
2023-03-22 13:31:58 -07:00
|
|
|
|
2023-03-23 12:52:38 -07:00
|
|
|
const { entityType, listKey } = parseEntitiesPath(expandedPath);
|
|
|
|
|
2023-03-23 13:30:45 -07:00
|
|
|
async function createEntity(data: Data, callbacks: CreateEntityCallbacks = {}): Promise<void> {
|
|
|
|
setIsLoading(true);
|
|
|
|
|
2023-03-22 13:31:58 -07:00
|
|
|
try {
|
2023-03-23 12:52:38 -07:00
|
|
|
const result = await api.request({
|
|
|
|
...toAxiosRequest(request),
|
|
|
|
data,
|
|
|
|
});
|
|
|
|
|
2023-03-22 13:31:58 -07:00
|
|
|
const schema = opts.schema || z.custom<TEntity>();
|
2023-03-23 12:52:38 -07:00
|
|
|
const entity = schema.parse(result.data);
|
2023-03-22 13:31:58 -07:00
|
|
|
|
|
|
|
// TODO: optimistic updating
|
|
|
|
dispatch(importEntities([entity], entityType, listKey));
|
|
|
|
|
|
|
|
if (callbacks.onSuccess) {
|
|
|
|
callbacks.onSuccess(entity);
|
|
|
|
}
|
|
|
|
} catch (error) {
|
|
|
|
if (callbacks.onError) {
|
|
|
|
callbacks.onError(error);
|
|
|
|
}
|
|
|
|
}
|
2023-03-23 13:30:45 -07:00
|
|
|
|
|
|
|
setIsLoading(false);
|
|
|
|
}
|
|
|
|
|
|
|
|
return {
|
|
|
|
createEntity,
|
|
|
|
isLoading,
|
2023-03-22 13:31:58 -07:00
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
export { useCreateEntity };
|