Skip to content

Commit

Permalink
refactor: wrap the bad request in invite function to make maintainable
Browse files Browse the repository at this point in the history
  • Loading branch information
mrgleam committed Oct 8, 2024
1 parent 7a95836 commit 8217d9c
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 21 deletions.
22 changes: 22 additions & 0 deletions src/app/error.gleam
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import gleam/io
import gleam/pgo
import gleam/result
import zeptomail.{type ApiError}

pub type AppError {
Expand All @@ -11,3 +13,23 @@ pub type AppError {
DatabaseError(pgo.QueryError)
ApiError(ApiError)
}

pub fn map_bad_request(r: Result(a, b)) -> Result(a, AppError) {
r
|> result.map_error(fn(error) {
io.debug(error)
case error {
_ -> BadRequest
}
})
}

pub fn try_bad_request(
result: Result(a, e1),
apply fun: fn(a) -> Result(b, e2),
) -> Result(b, AppError) {
case result {
Ok(x) -> map_bad_request(fun(x))
Error(_) -> Error(BadRequest)
}
}
35 changes: 14 additions & 21 deletions src/app/routes/user_routes.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import app/models/user.{
import app/pages
import app/pages/layout.{layout}
import app/web.{type Context, Context, bids_cookie, uid_cookie}
import gleam/function
import gleam/http.{Http}
import gleam/http/cookie
import gleam/http/response
Expand Down Expand Up @@ -345,30 +346,22 @@ pub fn post_invite(req: Request, ctx: Context) {
let email_validator = valid.string_is_email("Not email")

let result = {
use user_email <- result.try(
list.key_find(form.values, "email")
|> result.map_error(fn(_) { error.BadRequest }),
)
use user_email <-
error.try_bad_request(
list.key_find(form.values, "email"),
email_validator,
)
|> function.curry2(result.try)

use _valid <- result.try(
email_validator(user_email)
|> result.map_error(fn(err) {
io.debug(err)
error.BadRequest
}),
)
use user_id <-
error.try_bad_request(
result.map(get_user_by_email(user_email, ctx.db), fn(u) { u.id }),
uuid.cast,
)
|> function.curry2(result.try)

use board_id <- result.try(
list.key_find(form.values, "board")
|> result.map_error(fn(_) { error.BadRequest }),
)

use user_id <- result.try(
get_user_by_email(user_email, ctx.db)
|> result.map(fn(user) {
uuid.cast(user.id) |> result.map_error(fn(_) { error.BadRequest })
})
|> result.flatten,
error.map_bad_request(list.key_find(form.values, "board")),
)

use _ <- result.try(validate_board_user(user_id, ctx.db))
Expand Down

0 comments on commit 8217d9c

Please sign in to comment.