purescript-simple-json icon indicating copy to clipboard operation
purescript-simple-json copied to clipboard

How to use this library with Affjax?

Open diegovdc opened this issue 7 years ago • 5 comments

I know that might not be an issue with the library itself, but as Affjax is probably the most famous purescript library for ajax, it would make sense to be able to easily use Simple.JSON with it.

Currently I am getting the following error:

 Could not match type

    NonEmptyList ForeignError

  with type

    ResponseFormatError

It would be nice to have an easy way to have this transformation.

This is my code:

type MyRecordAlias =
  { userId :: Int
  , id :: Int
  , title :: String
  , completed :: Boolean
  }

main = void $ launchAff_ $ do
  res <- AX.request (
    AX.defaultRequest
    {
      url = "https://jsonplaceholder.typicode.com/todos/1",
      method = Left GET,
      responseFormat = ResponseFormat.string
    }
  )
  case res.body >>= JSON.readJSON  of
    Right (r :: MyRecordAlias) -> do
      log "all good"
    Left e -> do
      log "all bad"

diegovdc avatar Sep 14 '18 18:09 diegovdc

After a while, I think I got something. This might not be perfect, as I am quite a noob with purescript, but here it is:

transformError (ResponseFormat.ResponseFormatError e _) = cons' e Nil

main = void $ launchAff_ $ do
  res <- AX.request (
    AX.defaultRequest
    {
      url = "https://jsonplaceholder.typicode.com/todos/1",
      method = Left GET,
      responseFormat = ResponseFormat.string
    }
  )
 let body = bimap transfomError identity res.body
  case res.body >>= JSON.readJSON  of
    Right (r :: MyRecordAlias) -> do
      log "all good"
    Left e -> do
      log "all bad"

It was rather easy, perhaps a mention on the docs would be a good idea?

diegovdc avatar Sep 14 '18 19:09 diegovdc

Yeah, if you'd like you could put that in a new markdown file to go in the docs and PR it

justinwoo avatar Sep 15 '18 01:09 justinwoo

I'm not so sure about the transform code you have though, doesn't that just end up losing information? Might be better to return a nested either here

justinwoo avatar Sep 15 '18 01:09 justinwoo

Yeah, if you'd like you could put that in a new markdown file to go in the docs and PR it

Sure, but...

I'm not so sure about the transform code you have though, doesn't that just end up losing information? Might be better to return a nested either here

So if you can suggest improvements it would be great! (I did not know where to fit the Foreign part of ResponseFormatError )

diegovdc avatar Sep 15 '18 02:09 diegovdc

@diegovdc I'm using Variant to handle errors (see here)

dariooddenino avatar Oct 01 '18 12:10 dariooddenino