AffjaxSimpleJSONClient.purs 2.63 KB
Newer Older
1 2 3 4 5 6
module Gargantext.Components.GraphQL.AffjaxSimpleJSONClient
  (AffjaxClient(..))
  where

import Prelude

7
import Affjax.Web (Error(..), Response, URL, defaultRequest, printError, request)
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
import Affjax.RequestBody as RequestBody
import Affjax.RequestHeader (RequestHeader(..))
import Affjax.ResponseFormat as ResponseFormat
import Data.Argonaut.Core (Json)
import Data.Either (Either(..))
import Data.HTTP.Method as Method
import Data.List.NonEmpty as DLN
import Data.Maybe (Maybe(..))
import Data.MediaType.Common (applicationJSON)
import Effect.Aff (Aff, error, throwError)
import Foreign (unsafeToForeign)
import GraphQL.Client.Types (class QueryClient)
import Simple.JSON as JSON

data AffjaxClient
  = AffjaxClient URL (Array RequestHeader)
24
--
25 26 27 28 29
-- instance queryClient :: QueryClient AffjaxClient Unit Unit where
--   clientQuery _ (AffjaxClient url headers) name q vars = throwLeft =<< convertJsonResponse =<< queryPostForeign "query" url headers name q vars
--   clientMutation _ (AffjaxClient url headers) name q vars = throwLeft =<< convertJsonResponse =<< queryPostForeign "mutation" url headers name q vars
--   defQueryOpts = const unit
--   defMutationOpts = const unit
30
--
31 32 33 34
-- throwLeft :: forall r body. Either Error { body :: body | r } -> Aff body
-- throwLeft = case _ of
--   Left err -> throwError $ error $ printError err
--   Right { body } -> pure body
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
-- queryPostForeign ::
--   forall d.
--   JSON.WriteForeign d =>
--   String -> URL -> Array RequestHeader -> String -> String -> d -> Aff (Either Error (Response String))
-- queryPostForeign opStr url headers queryName q vars = do
--   request
--     defaultRequest
--       { withCredentials = true
--       , url = url
--       , method = Left Method.POST
--       --, responseFormat = ResponseFormat.json
--       , responseFormat = ResponseFormat.string
--       , content =
--         Just
--           -- $ RequestBody.Json
--           -- $ encodeJson
--           $ RequestBody.String
--           $ JSON.writeJSON
--               { query: opStr <> " " <> queryName <> " " <> q
--               , variables: vars
--               , operationName: queryName
--               }
--       , headers = headers <> [ ContentType applicationJSON ]
--       }
60
--
61 62 63 64 65
-- convertJsonResponse :: Either Error (Response String) -> Aff (Either Error (Response Json))
-- convertJsonResponse (Left err) = pure $ Left err
-- convertJsonResponse (Right res@{ body }) = pure $ case JSON.readJSON body of
--   Left err -> Left $ ResponseBodyError (DLN.head err) (res { body = unsafeToForeign body })
--   Right body' -> Right $ res { body = toJSON body' }
66
--
67
-- foreign import toJSON :: forall d. JSON.ReadForeign d => d -> Json
68 69
--
--