From 864b5f24ee558852bfdf15788e1c8db7808ff503 Mon Sep 17 00:00:00 2001 From: Philippe Pittoli Date: Sun, 21 May 2023 00:32:08 +0200 Subject: [PATCH] First try at doing JSON stuff. --- src/App/Messages.purs | 49 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 src/App/Messages.purs 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