Reputation: 41
as I'm very new to Haskell, could someone kindly push me into the correct direction of solving the following problem...?
I started with Yesod's scaffolding application. Serving HTML generated from database content works fine, but is there an elegant way to create plain text responses iterating over database tables? Simple plain text using a Handler like
getTestR = return . RepPlain . toContent ...
works too, but I'd like to serve:
config/models:
File
path Text
Conf
key Text
val Text
file FileId
as plaintext as in the SQL query:
select path, key, val from file, conf order by path, key;
As hamlet is for generating HTML, I think I must generate the response (iterate over the database contents) entirely in Haskell?
How do I convert between a database Entity and a Text (or Int, if the Row is of type Int), how do I convert from and to a database column Id?
Upvotes: 2
Views: 452
Reputation: 6738
with a plain text template!! ''#{expr}'' admits Text, String, Int32 or Int64 expressions as instances of Text.Shakespeare.Text.ToText
{-# LANGUAGE OverloadedStrings, ConstraintKinds #-}
module Handler.Plain where
import Import
import qualified Data.List as List
import Database.Persist.Sqlite
import qualified Data.Text as Text
import Control.Monad.Logger (MonadLogger)
import Control.Monad.Trans.Resource (MonadResourceBase)
import Text.Shakespeare.Text -- for the plain text template
stmt :: Text
stmt = "SELECT ??, ?? FROM File, Conf ON Conf.file = File.id ORDER BY File.path, Conf.key"
getQryResult :: (PersistQuery SqlPersist m, MonadLogger m, MonadResourceBase m) => () -> SqlPersist m [(Text, Text, Text)]
getQryResult () = do
result <- rawSql stmt []
return $ List.map getMyData (result :: [(Entity File, Entity Conf)])
where
getMyData (Entity _ file, Entity _ conf) = (filePath file, confKey conf, confVal conf)
getPlainR :: Handler RepPlain
getPlainR = do
result <- runDB $ getQryResult ()
return $ RepPlain $ toContent $ Text.unlines $ List.map formatMyData result
where
-- formatMyData (a, b, c) = Text.intercalate ", " [a,b,c]
-- with a plain text template:
formatMyData (a, b, c) = [st|
#{a}, #{b}, #{c} |]
Upvotes: 2