Skip to content

Commit

Permalink
refactor: port food POST route query handling.
Browse files Browse the repository at this point in the history
  • Loading branch information
n1k0 committed Sep 19, 2024
1 parent 964ab27 commit d767b70
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 10 deletions.
11 changes: 5 additions & 6 deletions src/Server.elm
Original file line number Diff line number Diff line change
Expand Up @@ -277,12 +277,11 @@ handleRequest db request =
|> respondWith 400

-- POST routes
Just (Route.FoodPostRecipe jsonBody) ->
jsonBody
|> handleDecodeBody BuilderQuery.decode
(\query ->
executeFoodQuery db (toFoodResults query) query
)
Just (Route.FoodPostRecipe (Ok foodQuery)) ->
executeFoodQuery db (toFoodResults foodQuery) foodQuery

Just (Route.FoodPostRecipe (Err error)) ->
( 400, Encode.string error )

Just (Route.TextilePostSimulator (Ok textileQuery)) ->
textileQuery
Expand Down
10 changes: 8 additions & 2 deletions src/Server/Route.elm
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ type Route
| FoodGetTransformList
-- POST
-- Food recipe builder (POST, JSON body)
| FoodPostRecipe Encode.Value
| FoodPostRecipe (Result String BuilderQuery.Query)
--
-- Textile Routes
-- GET
Expand Down Expand Up @@ -77,7 +77,7 @@ parser foodDb textile countries body =
, Parser.map FoodGetRecipe (s "GET" </> s "food" <?> Query.parseFoodQuery countries foodDb)

-- POST
, Parser.map (FoodPostRecipe body) (s "POST" </> s "food")
, Parser.map (FoodPostRecipe (decodeFoodQueryBody body)) (s "POST" </> s "food")

-- Textile
-- GET
Expand All @@ -96,6 +96,12 @@ parser foodDb textile countries body =
]


decodeFoodQueryBody : Encode.Value -> Result String BuilderQuery.Query
decodeFoodQueryBody body =
Decode.decodeValue BuilderQuery.decode body
|> Result.mapError Decode.errorToString


decodeTextileQueryBody : Encode.Value -> Result String TextileQuery.Query
decodeTextileQueryBody body =
Decode.decodeValue TextileQuery.decode body
Expand Down
4 changes: 2 additions & 2 deletions tests/Server/RouteTest.elm
Original file line number Diff line number Diff line change
Expand Up @@ -76,11 +76,11 @@ foodEndpoints db =
, describe "POST endpoints"
[ "/food"
|> testEndpoint db "POST" (FoodQuery.encode FoodQuery.empty)
|> Expect.equal (Just (Route.FoodPostRecipe (FoodQuery.encode FoodQuery.empty)))
|> Expect.equal (Just (Route.FoodPostRecipe (Ok FoodQuery.empty)))
|> asTest "should map the POST /food endpoint"
, "/food"
|> testEndpoint db "POST" Encode.null
|> Expect.equal (Just (Route.FoodPostRecipe Encode.null))
|> Expect.equal (Just (Route.FoodPostRecipe (Err "Problem with the given value:\n\nnull\n\nExpecting an OBJECT with a field named `ingredients`")))
|> asTest "should map the POST /food endpoint whatever the request body is"
]
, describe "validation"
Expand Down

0 comments on commit d767b70

Please sign in to comment.