diff --git a/src/App/Messages.purs b/src/App/Messages.purs new file mode 100644 index 0000000..e83d6dc --- /dev/null +++ b/src/App/Messages.purs @@ -0,0 +1,49 @@ +module App.Messages where + +import Effect (Effect) + +import Data.Argonaut.Core as J +import Data.Codec.Argonaut as CA +import Data.Either +import Data.Codec.Argonaut.Record as CAR + +-- Base types. +type Email = String +type Password = String +type Login = { email :: Email, password :: Password } +type Token = { token :: String } + +-- Their related JSON codecs. +login_codec ∷ CA.JsonCodec Login +login_codec = CA.object "Login" (CAR.record { email: CA.string, password: CA.string }) +token_codec ∷ CA.JsonCodec Token +token_codec = CA.object "Token" (CAR.record { token: CA.string }) + +-- All possible requests. +data RequestMessage + = MessageLogin Login + +-- All possible answers. +data AnswerMessage + = Logged Token + +encodeRequest ∷ RequestMessage → J.Json +encodeRequest m = case m of + (MessageLogin login) -> CA.encode login_codec login + +-- TODO +--rawSerialize :: RequestMessage -> ArrayBuffer +--rawDeserialize :: ArrayBuffer -> AnswerMessage + +data DecodeError + = JSONERROR CA.JsonDecodeError + | UnknownNumber + +decodeAnswer :: Int -> J.Json -> Either DecodeError AnswerMessage +decodeAnswer number json + = case number of + -- TODO: take right values + 11 -> case (CA.decode token_codec json) of + (Left err) -> Left (JSONERROR err) + (Right v) -> Right (Logged v) + _ -> Left UnknownNumber