elm-pages-v3-beta/examples/end-to-end/app/Api.elm

84 lines
2.3 KiB
Elm
Raw Normal View History

2022-02-25 21:04:19 +03:00
module Api exposing (routes)
import ApiRoute exposing (ApiRoute)
import DataSource exposing (DataSource)
import Html exposing (Html)
import Json.Decode as Decode
2022-03-01 04:45:16 +03:00
import Pages
import Random
2022-02-25 21:04:19 +03:00
import Route exposing (Route)
import Server.Request as Request
2022-03-01 04:45:16 +03:00
import Server.Response as Response exposing (Response)
2022-03-01 01:47:22 +03:00
import Test.Glob
2022-03-01 04:45:16 +03:00
import Test.Runner.Html
import Time
2022-02-25 21:04:19 +03:00
routes :
DataSource (List Route)
-> (Html Never -> String)
-> List (ApiRoute.ApiRoute ApiRoute.Response)
routes getStaticRoutes htmlToString =
2022-03-01 04:45:16 +03:00
let
html : Html Never -> Response data
html htmlValue =
{ statusCode = 200
, headers = [ ( "Content-Type", "text/html; charset=UTF-8" ) ]
, body = Just (htmlToString htmlValue)
, isBase64Encoded = False
}
|> Response.customResponse
in
2022-02-25 21:04:19 +03:00
[ greet
2022-03-01 04:45:16 +03:00
, ApiRoute.succeed
(Request.succeed
(Test.Glob.all
|> DataSource.map viewHtmlResults
|> DataSource.map html
)
)
|> ApiRoute.literal "tests"
|> ApiRoute.serverRender
2022-02-25 21:04:19 +03:00
]
2022-03-01 04:45:16 +03:00
config : Test.Runner.Html.Config
config =
Random.initialSeed (Pages.builtAt |> Time.posixToMillis)
|> Test.Runner.Html.defaultConfig
|> Test.Runner.Html.hidePassedTests
viewHtmlResults tests =
Html.div []
[ Html.h1 [] [ Html.text "My Test Suite" ]
, Html.div [] [ Test.Runner.Html.viewResults config tests ]
]
2022-02-25 21:04:19 +03:00
greet : ApiRoute ApiRoute.Response
greet =
ApiRoute.succeed
(Request.oneOf
[ Request.expectFormPost
(\{ field, optionalField } ->
field "first"
)
, Request.expectJsonBody (Decode.field "first" Decode.string)
, Request.expectQueryParam "first"
, Request.expectMultiPartFormPost
(\{ field, optionalField } ->
field "first"
)
]
|> Request.map
(\firstName ->
Response.plainText ("Hello " ++ firstName)
|> DataSource.succeed
)
)
|> ApiRoute.literal "api"
|> ApiRoute.slash
|> ApiRoute.literal "greet"
|> ApiRoute.serverRender