Search code examples
haskellmonadsyesod

How to avoid unsafePerformIO in the Handler Monad?


I have problems wrapping my head around avoiding an unsafePerformIO in a Yesod Handler. The code in the Handler is living in the Handler Monad, so how can I execute the IO operation?

getProfileR :: Handler Html
getProfileR = do

  -- toTMDBMovie's return-type is IO Movie
  -- Without the unsafePerformIO the type of result would be IO [Movie]
  -- How do I get from IO [Movie] to [Movie]?
  -- Ignore reccMovies - it's just a parameter.

  let result = unsafePerformIO $ mapM toTMDBMovie reccMovies

  defaultLayout $ do
      setTitle "Profile"
      $(widgetFile "profile")

Thank you for your help!


Solution

  • If a monad m you are working in is of MonadIO class, you can use liftIO :: IO a -> m a to perform IO actions inside.

    As for Yesod, you can perform IO action in its Handler actions, as well as Persistent's runDB blocks.