1{-# OPTIONS_GHC -fno-warn-orphans #-}
2{-# LANGUAGE OverloadedStrings #-}
3{-# LANGUAGE TemplateHaskell #-}
4{-# LANGUAGE ViewPatterns #-}
5
6module Hledger.Web.Application
7  ( makeApplication
8  , makeFoundation
9  ) where
10
11import Data.IORef (newIORef, writeIORef)
12import Network.Wai.Middleware.RequestLogger (logStdoutDev, logStdout)
13import Network.HTTP.Client (defaultManagerSettings)
14import Network.HTTP.Conduit (newManager)
15import Yesod.Default.Config
16
17import Hledger.Data (Journal, nulljournal)
18
19import Hledger.Web.Handler.AddR
20import Hledger.Web.Handler.MiscR
21import Hledger.Web.Handler.EditR
22import Hledger.Web.Handler.UploadR
23import Hledger.Web.Handler.JournalR
24import Hledger.Web.Handler.RegisterR
25import Hledger.Web.Import
26import Hledger.Web.WebOptions (WebOpts(serve_,serve_api_), corsPolicy)
27
28-- This line actually creates our YesodDispatch instance. It is the second half
29-- of the call to mkYesodData which occurs in Foundation.hs. Please see the
30-- comments there for more details.
31mkYesodDispatch "App" resourcesApp
32
33-- This function allocates resources (such as a database connection pool),
34-- performs initialization and creates a WAI application. This is also the
35-- place to put your migrate statements to have automatic database
36-- migrations handled by Yesod.
37makeApplication :: WebOpts -> Journal -> AppConfig DefaultEnv Extra -> IO Application
38makeApplication opts' j' conf' = do
39    foundation <- makeFoundation conf' opts'
40    writeIORef (appJournal foundation) j'
41    (logWare . (corsPolicy opts')) <$> toWaiApp foundation
42  where
43    logWare | development  = logStdoutDev
44            | serve_ opts' || serve_api_ opts' = logStdout
45            | otherwise    = id
46
47makeFoundation :: AppConfig DefaultEnv Extra -> WebOpts -> IO App
48makeFoundation conf opts' = do
49    manager <- newManager defaultManagerSettings
50    s <- staticSite
51    jref <- newIORef nulljournal
52    return $ App conf s manager opts' jref
53