Internal.hs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. {-# LANGUAGE ViewPatterns #-}
  2. module Codec.ActivityStream.Internal (commonOpts, commonOptsCC, ensure) where
  3. import Control.Monad (mzero)
  4. import Data.Aeson
  5. import Data.Aeson.TH
  6. import Data.Char
  7. import Data.HashMap.Strict (HashMap, member)
  8. import Data.Monoid ((<>))
  9. import Data.Text (Text, pack, unpack)
  10. ensure :: Monad m => String -> HashMap Text Value -> [Text] -> m ()
  11. ensure objName obj keys = mapM_ go keys
  12. where go k
  13. | member k obj = return ()
  14. | otherwise = fail ("Object \"" <> objName <>
  15. "\" does not contain property \"" <>
  16. unpack k <> "\"")
  17. toCamelCaseUpper :: String -> String
  18. toCamelCaseUpper = toCamelCase True
  19. toCamelCaseLower :: String -> String
  20. toCamelCaseLower = toCamelCase False
  21. toCamelCase :: Bool -> String -> String
  22. toCamelCase = go
  23. where go _ "" = ""
  24. go _ ('-':cs) = go True cs
  25. go True (c:cs) = toUpper c : go False cs
  26. go False (c:cs) = c : go False cs
  27. fromCamelCase :: String -> String
  28. fromCamelCase (c:cs)
  29. | isUpper c = toLower c : go cs
  30. | otherwise = go (c:cs)
  31. where go "" = ""
  32. go (c:cs)
  33. | c == ' ' = go cs
  34. | isUpper c = '-' : toLower c : go cs
  35. | otherwise = c : go cs
  36. commonOpts :: String -> Options
  37. commonOpts prefix = defaultOptions
  38. { fieldLabelModifier = drop (length prefix)
  39. , omitNothingFields = True
  40. }
  41. commonOptsCC :: String -> Options
  42. commonOptsCC prefix = defaultOptions
  43. { fieldLabelModifier = fromCamelCase . drop (length prefix)
  44. , constructorTagModifier = fromCamelCase
  45. , omitNothingFields = True
  46. }