Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yesod, WebSockets and Persistent

I'm trying to implement a server for a turn based game in Haskell. My choice would be to use Yesod for adminstration and meta-information (like, what games a user participates in and such).

I'd like to use web sockets to keep the in-game data overhead small.

Looking at the ws-chat example, I'm not sure how to get access to the Handler Monad and with it Persistent.

It would be perfect to have some bookkeeping-code for the connections wrapped around a "normal" Handler that itself updates the database and informs relevant users.

like image 460
Tobi Nary Avatar asked Feb 22 '13 19:02

Tobi Nary


2 Answers

This is how I think it should look like.

{-# LANGUAGE QuasiQuotes, TypeFamilies, GeneralizedNewtypeDeriving, TemplateHaskell, OverloadedStrings, GADTs, FlexibleContexts #-}
module Main where
import Control.Monad.IO.Class (liftIO)
import Data.String (fromString)
import Database.Persist
import Database.Persist.TH
import Database.Persist.Sqlite
import Network.Wai.Application.Static (staticApp, defaultWebAppSettings, defaultFileServerSettings)
import Network.Wai.Handler.Warp (runSettings, defaultSettings, settingsIntercept, settingsPort)
import Network.Wai.Handler.WebSockets (intercept)
import qualified Network.WebSockets as WS

share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistUpperCase|
Person
    name String
    age Int
    deriving Show
|]

ws :: WS.Request -> WS.WebSockets WS.Hybi10 ()
ws r = do
    WS.acceptRequest r
    liftIO $ runSqlite ":memory:" $ do
        runMigration migrateAll
        michaelId <- insert $ Person "Michael" 26
        michael <- get michaelId
        liftIO $ print michael

main :: IO ()
main = runSettings defaultSettings
    { settingsPort = 9160
    , settingsIntercept = intercept $ ws
    } $ staticApp (defaultFileServerSettings $ fromString ".")
like image 75
Gert Cuykens Avatar answered Nov 15 '22 00:11

Gert Cuykens


If you're looking to run a Handler monad yourself, you can use runFakeHandler.

like image 35
Michael Snoyman Avatar answered Nov 15 '22 00:11

Michael Snoyman