/
Utils.purs
56 lines (49 loc) · 1.48 KB
/
Utils.purs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
module Data.Argonaut.Decode.Struct.Utils
( elaborateFailure
, getMissingFieldErrorMessage
, notObjectErrorMessage
, reportJson
, reportObject
) where
import Prelude
import Data.Argonaut.Core (Json, toObject)
import Data.Argonaut.Decode.Class (class GDecodeJson, gDecodeJson)
import Data.Bifunctor (lmap)
import Data.Either (Either(Left, Right))
import Data.Maybe (Maybe(Just, Nothing))
import Data.Operator.Bottom (class Bottom2, bottom2)
import Data.Operator.Top (class Top1_, top1_)
import Foreign.Object (Object)
import Type.Data.RowList (RLProxy(RLProxy))
import Type.Row (class RowToList)
elaborateFailure :: forall a. String -> Either String a -> Either String a
elaborateFailure s e = lmap msg e
where
msg m = "Failed to decode key '" <> s <> "': " <> m
getMissingFieldErrorMessage :: String -> String
getMissingFieldErrorMessage fieldName =
"JSON was missing expected field: " <> fieldName
notObjectErrorMessage :: String
notObjectErrorMessage = "Could not convert JSON to object"
reportJson
:: forall a f
. Bottom2 f String
=> (Object Json -> f a)
-> Json
-> f a
reportJson f json =
case toObject json of
Just object -> f object
Nothing -> bottom2 notObjectErrorMessage
reportObject
:: forall f l r
. Bottom2 f String
=> GDecodeJson r l
=> RowToList r l
=> Top1_ f
=> Object Json
-> f (Record r)
reportObject object =
case gDecodeJson object (RLProxy :: RLProxy l) of
Left errorStr -> bottom2 errorStr
Right record -> top1_ record