Search code examples
haskellscotty

Dynamically importing modules in Haskell


I'm building a Scotty-based application and I'm trying to import and add a list of dynamic middlewares contained in a directory.

I don't want to hard-code my list of middleware - but as of now I'm using a Index.hs which expose all the directory middlewares.

Let's say I have a Main.hs

import Controllers.Index (endpoints)
...

main :: IO ()
main = do
  port <- read <$> getEnv "PORT"
  scotty port $ do
         middleware logStdoutDev
         endpoints

Then in Controllers/Index.hs:

module Controllers.Index
( endpoints ) where

import Controllers.Order (order)
import Controllers.User (user)
...
import Web.Scotty (ScottyM)

endpoints :: ScottyM ()
endpoints = order >> user >> ...

Each Controllers/*.hs contains a middleware.

What would be the best way to get rid of Controllers/Index.hs? Is there a way of importing all the modules from a directory and getting a list I can work with?


Solution

  • A little bit late, but this package helps to generate the needed imports from the setup, as suggested in the comments:

    https://hackage.haskell.org/package/imports