Internal.hs 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. {-# LANGUAGE ViewPatterns #-}
  2. module Codec.ActivityStream.Internal (commonOpts, commonOptsCC) where
  3. import Control.Monad (mzero)
  4. import Data.Aeson
  5. import Data.Aeson.TH
  6. import Data.Char
  7. import Data.Text (pack, unpack)
  8. import Network.URI (URI, parseURI)
  9. instance FromJSON URI where
  10. parseJSON (String ((parseURI . unpack) -> Just u)) = return u
  11. parseJSON _ = mzero
  12. instance ToJSON URI where
  13. toJSON = String . pack . show
  14. toCamelCaseUpper :: String -> String
  15. toCamelCaseUpper = toCamelCase True
  16. toCamelCaseLower :: String -> String
  17. toCamelCaseLower = toCamelCase False
  18. toCamelCase :: Bool -> String -> String
  19. toCamelCase = go
  20. where go _ "" = ""
  21. go _ ('-':cs) = go True cs
  22. go True (c:cs) = toUpper c : go False cs
  23. go False (c:cs) = c : go False cs
  24. fromCamelCase :: String -> String
  25. fromCamelCase (c:cs)
  26. | isUpper c = toLower c : go cs
  27. | otherwise = go (c:cs)
  28. where go "" = ""
  29. go (c:cs)
  30. | c == ' ' = go cs
  31. | isUpper c = '-' : toLower c : go cs
  32. | otherwise = c : go cs
  33. commonOpts :: String -> Options
  34. commonOpts prefix = defaultOptions
  35. { fieldLabelModifier = drop (length prefix)
  36. , omitNothingFields = True
  37. }
  38. commonOptsCC :: String -> Options
  39. commonOptsCC prefix = defaultOptions
  40. { fieldLabelModifier = fromCamelCase . drop (length prefix)
  41. , constructorTagModifier = fromCamelCase
  42. , omitNothingFields = True
  43. }