2 Module : Gargantext.Core.Utils.Prefix
4 Copyright : (c) CNRS, 2017-Present
5 License : AGPL + CECILL v3
6 Maintainer : team@gargantext.org
7 Stability : experimental
10 Here is a longer description of this module, containing some
11 commentary with @some markup@.
14 {-# LANGUAGE NoImplicitPrelude #-}
16 module Gargantext.Core.Utils.Prefix where
20 import Data.Aeson (Value, defaultOptions, parseJSON)
21 import Data.Aeson.TH (Options, fieldLabelModifier, omitNothingFields)
22 import Data.Aeson.Types (Parser)
23 import Data.Char (toLower)
24 import Data.Monoid ((<>))
25 import Text.Read (Read(..),readMaybe)
28 -- | Aeson Options that remove the prefix from fields
29 unPrefix :: String -> Options
30 unPrefix prefix = defaultOptions
31 { fieldLabelModifier = unCapitalize . dropPrefix prefix
32 , omitNothingFields = True
35 -- | Lower case leading character
36 unCapitalize :: String -> String
38 unCapitalize (c:cs) = toLower c : cs
39 --unCapitalize cs = map toLower cs
41 -- | Remove given prefix
42 dropPrefix :: String -> String -> String
43 dropPrefix prefix input = go prefix input
45 go pre [] = error $ conStringual $ "prefix leftover: " <> pre
47 go (p:preRest) (c:cRest)
48 | p == c = go preRest cRest
49 | otherwise = error $ conStringual $ "not equal: " <> (p:preRest) <> " " <> (c:cRest)
51 conStringual msg = "dropPrefix: " <> msg <> ". " <> prefix <> " " <> input
53 parseJSONFromString :: (Read a) => Value -> Parser a
54 parseJSONFromString v = do
55 numString <- parseJSON v
56 case readMaybe (numString :: String) of
57 Nothing -> fail $ "Invalid number for TransactionID: " ++ show v