PermissionLevel: codec fixed.

master
Philippe Pittoli 2023-05-31 00:22:38 +02:00
parent 5e6edd2f7f
commit 5b08ba5b54
2 changed files with 26 additions and 35 deletions

View File

@ -4,30 +4,27 @@ module AlternativeMain where
import Prelude
import Effect (Effect)
import Effect.Class (class MonadEffect, liftEffect)
import Effect.Class.Console as Console
import Data.Argonaut.Core as J
import Data.Codec.Argonaut as CA
import Data.Maybe (Maybe)
import Data.Argonaut.Decode as DAD
import Data.Either (Either(..))
import Data.Either (Either)
import Data.Codec.Argonaut.Record as CAR
import Data.UInt (fromInt, toInt, UInt)
import Data.Argonaut.Parser as JSONParser
import Data.Bifunctor (lmap)
import Data.Tuple (Tuple(..))
import App.PermissionLevel as PermissionLevel
type SumType = { permission :: PermissionLevel.PermissionLevel }
codecSumType = CA.object "SumType" (CAR.record { permission: PermissionLevel.codec })
type Permission = { permission :: PermissionLevel.PermissionLevel }
encode :: SumType -> String
encode = J.stringify <<< CA.encode codecSumType
codecPermission :: CA.JsonCodec Permission
codecPermission = CA.object "Permission" (CAR.record { permission: PermissionLevel.codec })
decode :: String -> Either String SumType
decode = parseDecodeJSON codecSumType
encode :: Permission -> String
encode = J.stringify <<< CA.encode codecPermission
decode :: String -> Either String Permission
decode = parseDecodeJSON codecPermission
parseDecodeJSON :: forall a. CA.JsonCodec a -> String -> Either String a
parseDecodeJSON codec str = do

View File

@ -1,13 +1,7 @@
module App.PermissionLevel where
import Prelude
import Data.Codec.Argonaut as CA
import Data.Codec.Argonaut.Variant as CAV
import Data.Variant as V
import Data.Profunctor (dimap)
import Data.Either (Either(..))
import Type.Proxy (Proxy(..))
import Data.Maybe (Maybe(..))
data PermissionLevel
= None
@ -15,22 +9,22 @@ data PermissionLevel
| Edit
| Admin
codec ∷ CA.JsonCodec PermissionLevel
-- | Codec for just encoding a single value of type `PermissionLevel`
codec :: CA.JsonCodec PermissionLevel
codec =
dimap toVariant fromVariant $ CAV.variantMatch { permission: Right CA.string }
CA.prismaticCodec "PermissionLevel" from to CA.string
where
toVariant = case _ of
None → V.inj (Proxy ∷ _ "permission") "none"
Read → V.inj (Proxy ∷ _ "permission") "read"
Edit → V.inj (Proxy ∷ _ "permission") "edit"
Admin → V.inj (Proxy ∷ _ "permission") "admin"
from :: String -> Maybe PermissionLevel
from = case _ of
"none" -> Just None
"read" -> Just Read
"edit" -> Just Edit
"admin" -> Just Admin
_ -> Nothing
fromVariant = V.match
{ permission:
\s -> case s of
"none" -> None
"read" -> Read
"edit" -> Edit
"admin" -> Admin
_ -> None
}
to :: PermissionLevel -> String
to = case _ of
None -> "none"
Read -> "read"
Edit -> "edit"
Admin -> "admin"