POST API safe type modeling

Haskell beginner is here trying to wrap the HTTP REST API in a safe way and with automatic decoding of Aeson return values. I started with a Haskell function for every API call. It was a bit arbitrary, but good.

To improve performance, I would like to turn each API call into its own data type. For example, to enter the system, I would like to simulate this as a type Loginthat indicates a method, a type Credentialsfor the method parameters and LoginReponsefor the result of the API call. Parameters and response types, of course, have corresponding FromJSON and ToJSON instances.

For two API calls, it looks something like this (using GADT):

data Void           = Void
data Credentials    = Credentials {...}
data LoginResponse  = LoginResponse {...}
data LogoutResponse = LogoutResponse {...}

data Command a where
    Login  :: Credentials -> Command LoginResponse
    Logout :: Void        -> Command LogoutResponse

execute :: FromJSON a => Command a -> IO a
execute cmd = do
    manager <- newManager tlsManagerSettings
    let request = buildHttpRequest cmd

    result <- httpLbs request manager
    let body = responseBody result
    let parsed = fromJust $ decode body

    return parsed

- , API, Aeson , !

, .

( Login Logout) , execute , , , Aeson.

- , .

, , !

+4
1

, - execute , buildHttpRequest, :

type Command a = Tagged a HttpRequest

( buildHttpRequest, - , HttpRequest. , , , . ) Tagged tagged ; . , , JSON execute.

execute , , :

execute :: FromJSON a => Command a -> IO a

; buildHttpRequest untag. , ; .

module FancyApp.Login (Credentials(..), LoginResponse(..), login) where

import FancyApp.Types

data Credentials = Credentials
data LoginResponse = LoginResponse

login :: Credentials -> Command LoginResponse
login = {- the old implementation of buildHttpRequest for Login -}

module FancyApp.Logout (LogoutResponse(..), logout) where

import FancyApp.Types

data LogoutResponse = LogoutResponse

logout :: Command LogoutResponse
logout = {- the old implementation of buildHttpRequest for Logout -}
+1

Source: https://habr.com/ru/post/1628389/


All Articles