Skip to content

Instantly share code, notes, and snippets.

@supermacro
Created March 31, 2019 21:09
Show Gist options
  • Save supermacro/295daae4f0811969e28bd82e7aa84535 to your computer and use it in GitHub Desktop.
Save supermacro/295daae4f0811969e28bd82e7aa84535 to your computer and use it in GitHub Desktop.
{-
Note that we use the `riskyRequest` function because this
webapp uses Cookies for authentication.
These cookies come from a different domain than the one
that host this app
-}
module Api exposing
( adminSignup
, adminSignin
, getAdminSession
)
import Http
import Json.Encode as E
import Api.Deserialize as D
import Api.Output as Output
api : String
api = "http://staging.api.parlez-vous.io/admins"
type alias ToMsg a msg = (Result Http.Error a -> msg)
type alias RequestTemplate =
{ method : String
, headers : List Http.Header
, tracker : Maybe String
, timeout : Maybe Float
}
type Method
= Get
| Post
requestFactory : Method -> RequestTemplate
requestFactory method =
let
( rawMethod, headers ) =
case method of
Get -> ( "GET", [] )
Post -> ( "POST", [ Http.header "Content-Type" "application/json" ] )
in
{ method = rawMethod
, headers = headers
, tracker = Nothing
, timeout = Nothing
}
post :
String ->
Http.Body ->
Http.Expect msg ->
Cmd msg
post endpoint body expect =
let
extraInfo = requestFactory Post
in
Http.riskyRequest
{ method = extraInfo.method
, url = api ++ endpoint
, headers = extraInfo.headers
, body = body
, expect = expect
, timeout = extraInfo.timeout
, tracker = extraInfo.tracker
}
get :
String ->
Http.Expect msg ->
Cmd msg
get endpoint expect =
let
extraInfo = requestFactory Get
in
Http.riskyRequest
{ method = extraInfo.method
, url = api ++ endpoint
, headers = extraInfo.headers
, body = Http.emptyBody
, expect = expect
, timeout = extraInfo.timeout
, tracker = extraInfo.tracker
}
adminSignup : ToMsg D.Admin msg -> Output.Signup -> Cmd msg
adminSignup toMsg data =
let
signupJson =
E.object
[ ( "username", E.string data.username )
, ( "password", E.string data.password )
, ( "passwordConfirm", E.string data.passwordConfirm )
]
body = Http.jsonBody signupJson
expect = Http.expectJson toMsg D.adminDecoder
in
post "/signup" body expect
adminSignin : ToMsg D.Admin msg -> Output.Signin -> Cmd msg
adminSignin toMsg data =
let
signinJson =
E.object
[ ( "username", E.string data.username )
, ( "password", E.string data.password )
]
body = Http.jsonBody signinJson
expect = Http.expectJson toMsg D.adminDecoder
in
post "/signin" body expect
getAdminSession : ToMsg D.Admin msg -> Cmd msg
getAdminSession toMsg =
let
expect = Http.expectJson toMsg D.adminDecoder
in
get "/profile" expect
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment