Architecture Custom Environment

strathausen edited this page Sep 13, 2010 · 2 revisions

Applications can add custom data to the Environment. In Config/App.hs, an application can define a custom AppEnvironment type. Then using the customSetupFilters, customPreFilters and customPostFilters, the application can manage its environment:

  1. customSetupFilters are called at the server startup and can be used to initialize the AppEnvironment (or conduct any other custom server startup activities).
  2. customPreFilters are called at the start of each request cycle and can be used to do manipulate the AppEnvironment (or conduct any other custom request activities).
  3. customPostFilters are similar to customPreFilters but are called after the request has been processed.


For a simple example, assume that the application wants to track the request count. Since the server can run many threads, the count needs to be held in an MVar. AppEnvironment might be defined as:

  data AppEnvironment = AppEnvironment (MVar Int)

  customSetupFilters = [setupAppEnvironment]
  customPreFilters = [incrementAppEnvironmentCounter]
  customPostFilters = [] -- Not used

  setupAppEnvironment = do e <- getEnvironment
                        counter <- newMVar 0
                        putEnvironment $ e {getAppEnvironment = Just $ AppEnvironment counter}

  incrementAppEnvironmentCounter = do e <- getEnvironment
                            let AppEnvironment mv = fromJust $ getAppEnvironment e
                            modifyMVar_ (return . (+1)) 

customPreFilters and customPostFilters

The most obvious usage of customPreFilters and customPostFilters is to handle authentication.

customPreFilters = [checkForValidUser]
customPostFilters = []