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 | module Utils ( uuid , shortId , now , toMaybe , logJson , encodeText ) where import qualified Data.UUID as UUID import qualified Data.UUID.V4 as UUID import qualified Data.Text.Encoding as T import qualified Data.Text as T import qualified Data.Time.Clock as Clock import qualified Data.Aeson as JSON import qualified Data.Aeson.Types as JSON import System.Random (randomRIO) import Control.Monad (replicateM) import Colog (LogAction (..)) import qualified Data.ByteString as BS import qualified Data.ByteString.Lazy as BSL (toStrict, toChunks) import Data.Aeson uuid :: IO T.Text uuid = T.decodeUtf8 . UUID.toASCIIBytes <$> UUID.nextRandom alphabet :: [Char] alphabet = ['a'..'z'] ++ ['A'..'Z'] ++ ['0'..'9'] shortId :: IO T.Text shortId = fmap T.pack $ replicateM 6 $ do i <- randomRIO (0, length alphabet - 1) return $ alphabet !! i now :: IO Clock.UTCTime now = Clock.getCurrentTime toMaybe :: [a] -> Maybe a toMaybe [] = Nothing toMaybe (a:_) = Just a logJson :: LogAction IO BS.ByteString -> [JSON.Pair] -> IO () logJson (LogAction logger) pairs = do logger $ BSL.toStrict $ JSON.encode $ JSON.object $ pairs encodeText :: ToJSON a => a -> T.Text encodeText = T.decodeUtf8 . BS.concat . BSL.toChunks . encode |