lpil / formal

29 stars 1 forks source link

Feature request: attach errors from the database exceptions to the Form record #6

Open ibarchenkov opened 3 days ago

ibarchenkov commented 3 days ago

Hey Louis, thanks for Gleam and this wonderful library! 🙏 I have a feature request that I believe would benefit many backend developers.

It would be helpful if formal provided a way to manually attach errors to the Form record after successful validation. This would cover scenarios where database-level validation is necessary, such as handling unique and exclusion constraint violations.

I'm unsure what an idiomatic API in Gleam would look like so here's an example to illustrate:

fn create_user(form_values) {
  let form_validator = { } // skipped for brevity

  // `finish2` is a hypothetical function that is similar `to finish/1`
  // but additionally returns the `Form` record for manual manipulation, e.g. to attach errors from the database
  case form.finish2(form_validator) {
    Ok(#(valid_user, form)) -> {
      case insert_user_into_database(valid_user) {
        Ok(_) -> render_created(201)

        // email uniqueness can't be validated inside `form_validator`
        Error(pgo.ConstraintViolated(_, "duplicate_email", _)) ->
          form
          // non-existent function
          |> form.put_error("email", "Must be unique")
          |> render_form(422)
      }
    }

    Error(form) -> {
      render_form(form, 422)
    }
  }
}
lpil commented 3 days ago

Ah yes! We need to cover this case. Thank you