inertiajs / inertia-phoenix

The Phoenix adapter for Inertia.js.
https://hexdocs.pm/inertia
Other
185 stars 8 forks source link

Error propagation #9

Closed derrickreimer closed 5 months ago

derrickreimer commented 5 months ago

We should add official support for propagating errors back to the Inertia client-side.

In order for your server-side validation errors to be available client-side, your server-side framework must share them via the errors prop. Inertia's first-party adapters, such as the Laravel adapter, do this automatically. For other frameworks, you may need to do this manually. Please refer to your specific server-side adapter documentation for more information.

https://inertiajs.com/validation

From a little type sleuthing, Inertia expects the props to contain errors:

https://github.com/inertiajs/inertia/blob/683155c8639aef8dc812c3fab4cdb5e2a35eccde/packages/core/src/types.ts#L31-L44

Errors and ErrorBag take the following shape:

https://github.com/inertiajs/inertia/blob/683155c8639aef8dc812c3fab4cdb5e2a35eccde/packages/core/src/types.ts#L9-L10

My thinking is we should add an assign_errors helper that accepts either an Ecto.Changeset or a bare map (that complies with the expected shapes). The helper should also be aware of the "error bag" specified in the request header (https://inertiajs.com/validation#error-bags).

Example

Given a request like this:

router.post('/companies', data, {
  errorBag: 'createCompany',
})

The incoming request should contain the error bag header (handled by Inertia):

X-Inertia-Error-Bag: createCompany

And if the request failed, we could set errors like this:

conn
|> assign_errors(changeset)

Which would result in the props containing errors automatically serialized and scoped under the proper bag name pulled from request headers:


{
  "props": {
    "errors": {
      "createCompany": {
        "name": "Name is required"
      }
    }
  }
}