|
| 1 | +{-# LANGUAGE OverloadedStrings #-} |
| 2 | +module MonadTransformers.ChapterExercises.HitCounter where |
| 3 | + |
| 4 | +import Control.Monad.Trans.Class |
| 5 | +import Control.Monad.Trans.Reader |
| 6 | +import Data.IORef |
| 7 | +import qualified Data.Map as M |
| 8 | +import Data.Maybe (fromMaybe) |
| 9 | +import Data.Text.Lazy (Text) |
| 10 | +import qualified Data.Text.Lazy as TL |
| 11 | +import System.Environment (getArgs) |
| 12 | +import Web.Scotty.Trans |
| 13 | +import Network.Wai.Internal |
| 14 | + |
| 15 | +data Config = |
| 16 | + Config { |
| 17 | + -- that's one, one click! |
| 18 | + -- two...two clicks! |
| 19 | + -- Three BEAUTIFUL clicks! ah ah ahhhh |
| 20 | + counts :: IORef (M.Map Text Integer) |
| 21 | + , prefix :: Text |
| 22 | + } |
| 23 | + |
| 24 | +-- Stuff inside ScottyT is, except for things that escape |
| 25 | +-- via IO, effectively read-only so we can't use StateT. |
| 26 | +-- It would overcomplicate things to attempt to do so and |
| 27 | +-- you should be using a proper database for production |
| 28 | +-- applications. |
| 29 | +type Scotty = ScottyT Text (ReaderT Config IO) |
| 30 | +type Handler = ActionT Text (ReaderT Config IO) |
| 31 | + |
| 32 | +bumpBoomp :: Text |
| 33 | + -> M.Map Text Integer |
| 34 | + -> (M.Map Text Integer, Integer) |
| 35 | +bumpBoomp k m = (newM, n) |
| 36 | + where n = M.findWithDefault 1 k m |
| 37 | + newM = M.insert k (n + 1) m |
| 38 | + |
| 39 | +updateAndGet :: Text -> Config -> IO Integer |
| 40 | +updateAndGet key config = do |
| 41 | + let counter = counts config :: IORef (M.Map Text Integer) |
| 42 | + (m, n) <- bumpBoomp key <$> (readIORef counter :: IO (M.Map Text Integer)) |
| 43 | + -- Very important to use writeIORef or something equivalent |
| 44 | + -- otherwise the counter will not be updated |
| 45 | + writeIORef counter m |
| 46 | + return n |
| 47 | + |
| 48 | +app :: Scotty () |
| 49 | +app = get "/:key" $ do |
| 50 | + unprefixed <- param "key" |
| 51 | + p <- lift $ ReaderT (return . prefix) |
| 52 | + let key' = mappend p unprefixed |
| 53 | + newInteger <- lift $ ReaderT $ updateAndGet key' |
| 54 | + html $ mconcat [ "<h1>Success! Count was: " |
| 55 | + , TL.pack $ show newInteger |
| 56 | + , "</h1>" |
| 57 | + ] |
| 58 | + |
| 59 | +main :: IO () |
| 60 | +main = do |
| 61 | + [prefixArg] <- getArgs |
| 62 | + counter <- newIORef M.empty |
| 63 | + let config = Config counter (TL.pack prefixArg) |
| 64 | + runR = flip runReaderT config :: ReaderT Config IO Response -> IO Response |
| 65 | + scottyT 3000 runR app |
0 commit comments