REST.purs 2.14 KB
Newer Older
1
module Gargantext.Config.REST where
2

Sudhir Kumar's avatar
Sudhir Kumar committed
3
import Affjax (defaultRequest, printResponseFormatError, request)
4
import Affjax.RequestBody (RequestBody(..))
Sudhir Kumar's avatar
Sudhir Kumar committed
5
import Affjax.RequestHeader (RequestHeader(..))
Sudhir Kumar's avatar
Sudhir Kumar committed
6
import Affjax.ResponseFormat as ResponseFormat
7
import Data.Argonaut (class DecodeJson, decodeJson, class EncodeJson, encodeJson)
8
import Data.Either (Either(..))
Sudhir Kumar's avatar
Sudhir Kumar committed
9
import Data.HTTP.Method (Method(..))
10
import Data.Maybe (Maybe(..))
Sudhir Kumar's avatar
Sudhir Kumar committed
11
import Data.MediaType.Common (applicationJSON)
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
import Effect.Aff (Aff, throwError)
import Effect.Exception (error)

import Gargantext.Prelude

send :: forall a b. EncodeJson a => DecodeJson b =>
        Method -> String -> Maybe a -> Aff b
send m url reqbody = do
  affResp <- request $ defaultRequest
         { url = url
         , responseFormat = ResponseFormat.json
         , method = Left m
         , headers =  [ ContentType applicationJSON
                      , Accept applicationJSON
                        --   , RequestHeader "Authorization" $  "Bearer " <> token
                      ]
         , content  = (Json <<< encodeJson) <$> reqbody
         }
Sudhir Kumar's avatar
Sudhir Kumar committed
30
  case affResp.body of
31
    Left err -> do
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
      _ <-  logs $ printResponseFormatError err
      throwError $ error $ printResponseFormatError err
    Right json -> do
      --_ <-  logs $ show json.status
      --_ <-  logs $ show json.headers
      --_ <-  logs $ show json.body
      case decodeJson json of
        Left err -> throwError $ error $ "decodeJson affResp.body: " <> err
        Right b -> pure b

noReqBody :: Maybe Unit
noReqBody = Nothing

get :: forall a. DecodeJson a => String -> Aff a
get url = send GET url noReqBody

put :: forall a b. EncodeJson a => DecodeJson b => String -> a -> Aff b
put url = send PUT url <<< Just

delete :: forall a. DecodeJson a => String -> Aff a
delete url = send DELETE url noReqBody

54 55 56 57 58
-- This might not be a good idea:
-- https://stackoverflow.com/questions/14323716/restful-alternatives-to-delete-request-body
deleteWithBody :: forall a b. EncodeJson a => DecodeJson b => String -> a -> Aff b
deleteWithBody url = send DELETE url <<< Just

59 60
post :: forall a b. EncodeJson a => DecodeJson b => String -> a -> Aff b
post url = send POST url <<< Just