So I started working on the Purescript implementation. Code here.
My first objective is to get the JSON data served by the backend into the app.
I followed the purescript-foreign
examples from @garyb …
There’s a couple of things I want the code to do that I can’t get it to do, plus a couple of questions – I would appreciate some help so I can continue as a the moment I am stuck
- In my implementation the type
Question
should have a chosenAnswer
field for , this is commeted out in the above. This field indicates which answer the player clicks, and unless the click event has registered it should be Nothing
.
- How do I get this
Nothing
into my readQuestion
function? I tried fromMaybe
or just readNullOrUndefined
but I get a Maybe foreign
return type…
-- Read JSON question into a Foreign type
readQuestion :: Foreign -> F Question
readQuestion value = do
questionText <- value ! "questionText" >>= readString
answers <- value ! "answers" >>= readArray >>= traverse readString
correctAnswer <- value ! "correctAnswer" >>= readInt
-- chosenAnswer <- value ! "" >>= fromMaybe readNullOrUndefined Nothing
-- pure { questionText, answers, correctAnswer, chosenAnswer }
pure { questionText, answers, correctAnswer }
- For the moment all the
main
function is checking
if I read the JSON ok.
- I copied the Util/foreign value from the examples, is it required to read my
json
?
module Utils.Value where
import Prelude
import Data.Function.Uncurried (Fn3, runFn3)
import Foreign (F, Foreign, ForeignError(..), fail)
foreign import foreignValueImpl :: forall r. Fn3 (String -> r) (Foreign -> r) String r
foreignValue :: String -> F Foreign
foreignValue json = runFn3 foreignValueImpl (fail <<< ForeignError) pure json
"use strict";
exports.foreignValueImpl = function (left, right, str) {
try {
return right(JSON.parse(str));
} catch (e) {
return left(e.toString());
}
};
I understand the JavaScript implementation handles the error on Left
and parses the JSON on Right
, but I am not sure this might be complicating things down the line when I need to access the Question
type?
For example I will want to access the Question
later to do something like
initialState :: State
initialState = { score: 0, questions: [], waitingForQuestion: true }
appendQuestion :: Question -> State -> State
appendQuestion question state =
if state.waitingForQuestion
then state { questions = snoc state.questions question,
waitingForQuestion = false }
else state