First try at doing JSON stuff.

This commit is contained in:
Philippe Pittoli 2023-05-21 00:32:08 +02:00
parent ef623b8f1c
commit 864b5f24ee

49
src/App/Messages.purs Normal file
View File

@ -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