UNPKG

ra-core

Version:

Core components of react-admin, a frontend Framework for building admin applications on top of REST services, using ES6, React

154 lines 6.23 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.useCreateController = void 0; const react_1 = require("react"); const auth_1 = require("../../auth/index.cjs"); const dataProvider_1 = require("../../dataProvider/index.cjs"); const routing_1 = require("../../routing/index.cjs"); const notification_1 = require("../../notification/index.cjs"); const saveContext_1 = require("../saveContext/index.cjs"); const i18n_1 = require("../../i18n/index.cjs"); const core_1 = require("../../core/index.cjs"); /** * Prepare data for the Create view * * @param {Object} props The props passed to the Create component. * * @return {Object} controllerProps Fetched data and callbacks for the Create view * * @example * * import { useCreateController } from 'react-admin'; * import CreateView from './CreateView'; * * const MyCreate = props => { * const controllerProps = useCreateController(props); * return <CreateView {...controllerProps} {...props} />; * } */ const useCreateController = (props = {}) => { const { disableAuthentication, record, redirect: redirectTo, transform, mutationMode = 'pessimistic', mutationOptions = {}, } = props; const resource = (0, core_1.useResourceContext)(props); if (!resource) { throw new Error('useCreateController requires a non-empty resource prop or context'); } const { isPending: isPendingAuthenticated } = (0, auth_1.useAuthenticated)({ enabled: !disableAuthentication, }); const { isPending: isPendingCanAccess } = (0, auth_1.useRequireAccess)({ action: 'create', resource, enabled: !disableAuthentication && !isPendingAuthenticated, }); const { hasEdit, hasShow } = (0, core_1.useResourceDefinition)(props); const finalRedirectTo = redirectTo ?? getDefaultRedirectRoute(hasShow, hasEdit); const translate = (0, i18n_1.useTranslate)(); const notify = (0, notification_1.useNotify)(); const redirect = (0, routing_1.useRedirect)(); const { onSuccess, onError, meta, ...otherMutationOptions } = mutationOptions; const { registerMutationMiddleware, getMutateWithMiddlewares, unregisterMutationMiddleware, } = (0, saveContext_1.useMutationMiddlewares)(); const [create, { isPending: saving }] = (0, dataProvider_1.useCreate)(resource, undefined, { onSuccess: async (...args) => { if (onSuccess) { return onSuccess(...args); } const [data] = args; notify(`resources.${resource}.notifications.created`, { type: 'info', messageArgs: { smart_count: 1, _: translate(`ra.notification.created`, { smart_count: 1, }), }, undoable: mutationMode === 'undoable', }); redirect(finalRedirectTo, resource, data.id, data); }, onError: (...args) => { if (onError) { return onError(...args); } const [error] = args; // Don't trigger a notification if this is a validation error // (notification will be handled by the useNotifyIsFormInvalid hook) const validationErrors = error?.body?.errors; const hasValidationErrors = !!validationErrors && Object.keys(validationErrors).length > 0; if (!hasValidationErrors || mutationMode !== 'pessimistic') { notify(typeof error === 'string' ? error : error.message || 'ra.notification.http_error', { type: 'error', messageArgs: { _: typeof error === 'string' ? error : error instanceof Error || (typeof error === 'object' && error !== null && error.hasOwnProperty('message')) ? // @ts-ignore error.message : undefined, }, }); } }, ...otherMutationOptions, mutationMode, returnPromise: mutationMode === 'pessimistic', getMutateWithMiddlewares, }); const save = (0, react_1.useCallback)((data, { onSuccess: onSuccessFromSave, onError: onErrorFromSave, transform: transformFromSave, meta: metaFromSave, } = {}) => Promise.resolve(transformFromSave ? transformFromSave(data) : transform ? transform(data) : data).then(async (data) => { try { await create(resource, { data, meta: metaFromSave ?? meta }, { onError: onErrorFromSave, onSuccess: onSuccessFromSave, }); } catch (error) { if ((error instanceof dataProvider_1.HttpError || (typeof error === 'object' && error !== null && error.hasOwnProperty('body'))) && error.body?.errors != null) { return error.body.errors; } } }), [create, meta, resource, transform]); const getResourceLabel = (0, core_1.useGetResourceLabel)(); const defaultTitle = translate(`resources.${resource}.page.create`, { _: translate('ra.page.create', { name: getResourceLabel(resource, 1), }), }); return { isFetching: false, isLoading: false, isPending: disableAuthentication ? false : isPendingCanAccess, mutationMode, saving, defaultTitle, save, record, resource, redirect: finalRedirectTo, registerMutationMiddleware, unregisterMutationMiddleware, }; }; exports.useCreateController = useCreateController; const getDefaultRedirectRoute = (hasShow, hasEdit) => { if (hasEdit) { return 'edit'; } if (hasShow) { return 'show'; } return 'list'; }; //# sourceMappingURL=useCreateController.js.map