This repository was archived by the owner on Sep 13, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathAPI.elm
71 lines (53 loc) · 1.7 KB
/
API.elm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
port module Forms.API exposing (main)
import Json.Decode exposing (Decoder, decodeValue, int, map, string)
import Json.Decode.Pipeline exposing (decode, required)
import Serverless
import Serverless.Conn exposing (method, request, respond, textBody)
import Serverless.Conn.Request exposing (Method(..), asJson, body)
{-| Shows one way to convert a JSON POST body into Elm data
-}
main : Serverless.Program () () () () ()
main =
Serverless.httpApi
{ configDecoder = Serverless.noConfig
, initialModel = ()
, parseRoute = Serverless.noRoutes
, update = Serverless.noSideEffects
, interop = Serverless.noInterop
, requestPort = requestPort
, responsePort = responsePort
-- Entry point for new connections.
, endpoint = endpoint
}
type alias Person =
{ name : String
, age : Int
}
endpoint : Conn -> ( Conn, Cmd () )
endpoint conn =
case
( method conn
, conn
|> (request >> body >> asJson)
|> Result.andThen (decodeValue personDecoder)
)
of
( POST, Ok person ) ->
respond ( 200, textBody <| toString person ) conn
( POST, Err err ) ->
respond
( 400
, textBody <| "Could not decode request body. " ++ err
)
conn
_ ->
respond ( 405, textBody "Method not allowed" ) conn
personDecoder : Decoder Person
personDecoder =
decode Person
|> required "name" string
|> required "age" int
type alias Conn =
Serverless.Conn.Conn () () () ()
port requestPort : Serverless.RequestPort msg
port responsePort : Serverless.ResponsePort msg