-
-
Notifications
You must be signed in to change notification settings - Fork 5.3k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add server side validation support #7938
Changes from 3 commits
267e755
f96df58
fa7b88d
0625ac2
bb4ed6e
26ba43d
71fa7de
ba28552
03c8bac
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -320,42 +320,46 @@ const CustomerCreate = () => ( | |
|
||
## Server-Side Validation | ||
|
||
You can use the errors returned by the dataProvider mutation as a source for the validation. In order to display the validation errors, a custom `save` function needs to be used: | ||
Server-side validation is supported out of the box. It requires that the dataProvider throws an error with the following shape: | ||
|
||
{% raw %} | ||
```jsx | ||
import * as React from 'react'; | ||
import { useCallback } from 'react'; | ||
import { Create, SimpleForm, TextInput, useCreate } from 'react-admin'; | ||
|
||
export const UserCreate = () => { | ||
const [create] = useCreate(); | ||
const save = useCallback( | ||
async values => { | ||
try { | ||
await create('users', { data: values }, { returnPromise: true }); | ||
} catch (error) { | ||
if (error.body.errors) { | ||
// The shape of the returned validation errors must match the shape of the form | ||
return error.body.errors; | ||
} | ||
} | ||
}, | ||
[create] | ||
); | ||
|
||
return ( | ||
<Create> | ||
<SimpleForm onSubmit={save}> | ||
<TextInput label="First Name" source="firstName" /> | ||
<TextInput label="Age" source="age" /> | ||
</SimpleForm> | ||
</Create> | ||
); | ||
}; | ||
``` | ||
{% endraw %} | ||
{ | ||
body: { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. why the "body" key? Why can't the dataProvider only reject with Also, your snippet is both a type description and an example, and so it's not enough informative. I'd use a more complete example:
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Because that's the current shape of our |
||
errors: { | ||
source: 'error message', | ||
} | ||
} | ||
} | ||
``` | ||
|
||
**Tip**: The shape of the returned validation errors must correspond to the form: a key needs to match a `source` prop. | ||
**Tip**: The shape of the returned validation errors must match the form shape: each key needs to match a `source` prop. | ||
|
||
**Tip**: The returned validation errors might have any validation format we support (simple strings or object with message and args) for each key. | ||
slax57 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
**Tip**: If your data provider leverages our [`httpClient`](https://marmelab.com/react-admin/DataProviderWriting.html#example-rest-implementation), this will be handled automatically when your server returns an invalid response with a json body containing the `errors` key. | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. this isn't super clear There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I tried to make this section clearer. Please let me know if that's enough. |
||
|
||
Here's an example of a dataProvider not using our `httpClient`: | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. again, this is confusing. You don't give an eample of the general case but you give one of a particular case. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. same |
||
|
||
```js | ||
const myDataProvider = { | ||
create: async (resource, { data }) => { | ||
const response = await fetch(`${process.env.API_URL}/${resource}`, { | ||
method: 'POST', | ||
body: JSON.stringify(data), | ||
}); | ||
|
||
const body = response.json(); | ||
|
||
if (status < 200 || status >= 300) { | ||
// Here, we expect the body to contains an `errors` key | ||
throw new HttpError( | ||
(body && body.message) || statusText, | ||
status, | ||
body | ||
); | ||
} | ||
|
||
return body; | ||
} | ||
} | ||
``` |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -6,7 +6,11 @@ import { Location } from 'history'; | |
import { UseMutationOptions } from 'react-query'; | ||
|
||
import { useAuthenticated } from '../../auth'; | ||
import { useCreate, UseCreateMutateParams } from '../../dataProvider'; | ||
import { | ||
HttpError, | ||
useCreate, | ||
UseCreateMutateParams, | ||
} from '../../dataProvider'; | ||
import { useRedirect, RedirectionSideEffect } from '../../routing'; | ||
import { useNotify } from '../../notification'; | ||
import { SaveContextValue, useMutationMiddlewares } from '../saveContext'; | ||
|
@@ -74,7 +78,7 @@ export const useCreateController = < | |
const [create, { isLoading: saving }] = useCreate< | ||
RecordType, | ||
MutationOptionsError | ||
>(resource, undefined, otherMutationOptions); | ||
>(resource, undefined, { ...otherMutationOptions, returnPromise: true }); | ||
|
||
const save = useCallback( | ||
( | ||
|
@@ -91,55 +95,67 @@ export const useCreateController = < | |
: transform | ||
? transform(data) | ||
: data | ||
).then((data: Partial<RecordType>) => { | ||
).then(async (data: Partial<RecordType>) => { | ||
const mutate = getMutateWithMiddlewares(create); | ||
mutate( | ||
resource, | ||
{ data, meta }, | ||
{ | ||
onSuccess: async (data, variables, context) => { | ||
if (onSuccessFromSave) { | ||
return onSuccessFromSave( | ||
data, | ||
variables, | ||
context | ||
); | ||
} | ||
if (onSuccess) { | ||
return onSuccess(data, variables, context); | ||
} | ||
try { | ||
await mutate( | ||
resource, | ||
{ data, meta }, | ||
{ | ||
onSuccess: async (data, variables, context) => { | ||
if (onSuccessFromSave) { | ||
return onSuccessFromSave( | ||
data, | ||
variables, | ||
context | ||
); | ||
} | ||
if (onSuccess) { | ||
return onSuccess(data, variables, context); | ||
} | ||
|
||
notify('ra.notification.created', { | ||
type: 'info', | ||
messageArgs: { smart_count: 1 }, | ||
}); | ||
redirect(finalRedirectTo, resource, data.id, data); | ||
}, | ||
onError: onErrorFromSave | ||
? onErrorFromSave | ||
: onError | ||
? onError | ||
: (error: Error) => { | ||
notify( | ||
typeof error === 'string' | ||
? error | ||
: error.message || | ||
'ra.notification.http_error', | ||
{ | ||
type: 'warning', | ||
messageArgs: { | ||
_: | ||
typeof error === 'string' | ||
? error | ||
: error && error.message | ||
? error.message | ||
: undefined, | ||
}, | ||
} | ||
); | ||
}, | ||
notify('ra.notification.created', { | ||
type: 'info', | ||
messageArgs: { smart_count: 1 }, | ||
}); | ||
redirect( | ||
finalRedirectTo, | ||
resource, | ||
data.id, | ||
data | ||
); | ||
}, | ||
onError: onErrorFromSave | ||
? onErrorFromSave | ||
: onError | ||
? onError | ||
: (error: Error) => { | ||
notify( | ||
typeof error === 'string' | ||
? error | ||
: error.message || | ||
'ra.notification.http_error', | ||
{ | ||
type: 'warning', | ||
messageArgs: { | ||
_: | ||
typeof error === 'string' | ||
? error | ||
: error && | ||
error.message | ||
? error.message | ||
: undefined, | ||
}, | ||
} | ||
); | ||
}, | ||
} | ||
); | ||
} catch (error) { | ||
if ((error as HttpError).body?.errors != null) { | ||
return (error as HttpError).body.errors; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This is weird: the save promise resolves when there is a validation error in the save process? I'd expect it to reject. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This is how the There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. can't we improve that in a backward compatible way? |
||
} | ||
); | ||
} | ||
djhi marked this conversation as resolved.
Show resolved
Hide resolved
|
||
}), | ||
[ | ||
create, | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Does that work even in optimistic mode?