Initializing data in the foundation datatype

This example is meant to demonstrate a relatively simple concept: performing some initialization of data to be kept in the foundation datatype. There are various reasons to do this, though the two most important are:

  • Efficiency: by initializing data once, at process startup, you can avoid having to recompute the same value in each request.

  • Persistence: we want to store some information in a mutable location which will be persisted between individual requests. Often times, this is done via an external database, but it can also be done via an in-memory mutable variable.

While mutable variables can be a convenient storage mechanism, remember that they have some downsides. If your process dies, you lose your data. Also, if you scale horizontally to more than one process, you’ll need some way to synchronize the data between processes. We’ll punt on both of those issues for this example, but the problems are real. This is one of the reasons Yesod puts such a strong emphasis on using an external database for persistence.

To demonstrate, we’ll implement a very simple website. It will contain a single route, and will serve content stored in a Markdown file. In addition to serving that content, we’ll also display an old-school visitor counter indicating how many visitors have been to the site.

Step 1: define your foundation

We’ve identified two pieces of information to be initialized: the Markdown content to be display on the homepage, and a mutable variable holding the visitor count. Remember that our goal is to perform as much of the work in the initialization phase as possible and thereby avoid performing the same work in the handlers themselves. Therefore, we want to preprocess the Markdown content into HTML. As for the visitor count, a simple IORef should be sufficient. So our foundation data type is:

  1. data App = App
  2. { homepageContent :: Html
  3. , visitorCount :: IORef Int
  4. }

Step 2: use the foundation

For this trivial example, we only have one route: the homepage. All we need to do is:

  1. Increment the visitor count.

  2. Get the new visitor count.

  3. Display the Markdown content together with the visitor count.

One trick we’ll use to make the code a bit shorter is to utilize record wildcard syntax: App {..}. This is convenient when we want to deal with a number of different fields in a datatype.

  1. getHomeR :: Handler Html
  2. getHomeR = do
  3. App {..} <- getYesod
  4. currentCount <- liftIO $ atomicModifyIORef visitorCount
  5. $ \i -> (i + 1, i + 1)
  6. defaultLayout $ do
  7. setTitle "Homepage"
  8. [whamlet|
  9. <article>#{homepageContent}
  10. <p>You are visitor number: #{currentCount}.
  11. |]

Step 3: create the foundation value

When we initialize our application, we’ll now need to provide values for the two fields we described above. This is normal IO code, and can perform any arbitrary actions needed. In our case, we need to:

  1. Read the Markdown from the file.

  2. Convert that Markdown to HTML.

  3. Create the visitor counter variable.

The code ends up being just as simple as those steps imply:

  1. go :: IO ()
  2. go = do
  3. rawMarkdown <- TLIO.readFile "homepage.md"
  4. countRef <- newIORef 0
  5. warp 3000 App
  6. { homepageContent = markdown def rawMarkdown
  7. , visitorCount = countRef
  8. }

Conclusion

There’s no rocket science involved in this example, just very straightforward programming. The purpose of this chapter is to demonstrate the commonly used best practice for achieving these often needed objectives. In your own applications, the initialization steps will likely be much more complicated: setting up database connection pools, starting background jobs to batch process large data, or anything else. After reading this chapter, you should now have a good idea of where to place your application-specific initialization code.

Below is the full source code for the example described above:

  1. {-# LANGUAGE OverloadedStrings #-}
  2. {-# LANGUAGE QuasiQuotes #-}
  3. {-# LANGUAGE RecordWildCards #-}
  4. {-# LANGUAGE TemplateHaskell #-}
  5. {-# LANGUAGE TypeFamilies #-}
  6. import Data.IORef
  7. import qualified Data.Text.Lazy.IO as TLIO
  8. import Text.Markdown
  9. import Yesod
  10. data App = App
  11. { homepageContent :: Html
  12. , visitorCount :: IORef Int
  13. }
  14. mkYesod "App" [parseRoutes|
  15. / HomeR GET
  16. |]
  17. instance Yesod App
  18. getHomeR :: Handler Html
  19. getHomeR = do
  20. App {..} <- getYesod
  21. currentCount <- liftIO $ atomicModifyIORef visitorCount
  22. $ \i -> (i + 1, i + 1)
  23. defaultLayout $ do
  24. setTitle "Homepage"
  25. [whamlet|
  26. <article>#{homepageContent}
  27. <p>You are visitor number: #{currentCount}.
  28. |]
  29. main :: IO ()
  30. main = do
  31. rawMarkdown <- TLIO.readFile "homepage.md"
  32. countRef <- newIORef 0
  33. warp 3000 App
  34. { homepageContent = markdown def rawMarkdown
  35. , visitorCount = countRef
  36. }