justinwoo / purescript-simple-json

A simple Purescript JSON library that uses types automatically
http://purescript-simple-json.readthedocs.io
MIT License
133 stars 45 forks source link

How to use this library with Affjax? #51

Open diegovdc opened 6 years ago

diegovdc commented 6 years ago

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 commented 6 years ago

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?

justinwoo commented 6 years ago

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

justinwoo commented 6 years ago

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

diegovdc commented 6 years ago

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)

dariooddenino commented 6 years ago

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