2 module Gargantext.Utils.Prefix where
6 import Data.Aeson (Value, defaultOptions, parseJSON)
7 import Data.Aeson.TH (Options, fieldLabelModifier, omitNothingFields)
8 import Data.Aeson.Types (Parser)
9 import Data.Char (toLower)
10 import Data.Monoid ((<>))
11 import Text.Read (Read(..),readMaybe)
14 -- | Aeson Options that remove the prefix from fields
15 unPrefix :: String -> Options
16 unPrefix prefix = defaultOptions
17 { fieldLabelModifier = unCapitalize . dropPrefix prefix
18 , omitNothingFields = True
21 -- | Lower case leading character
22 unCapitalize :: String -> String
24 unCapitalize (c:cs) = toLower c : cs
26 -- | Remove given prefix
27 dropPrefix :: String -> String -> String
28 dropPrefix prefix input = go prefix input
30 go pre [] = error $ conStringual $ "prefix leftover: " <> pre
32 go (p:preRest) (c:cRest)
33 | p == c = go preRest cRest
34 | otherwise = error $ conStringual $ "not equal: " <> (p:preRest) <> " " <> (c:cRest)
36 conStringual msg = "dropPrefix: " <> msg <> ". " <> prefix <> " " <> input
38 parseJSONFromString :: (Read a) => Value -> Parser a
39 parseJSONFromString v = do
40 numString <- parseJSON v
41 case readMaybe (numString :: String) of
42 Nothing -> fail $ "Invalid number for TransactionID: " ++ show v