Search code examples
haskellpersistenceyesod

convert PersistValue to Text in Yesod


I want get the attribute value from Persist Entity; so i have the following code

userToText userId = do
    user <- runDB $ get404 userId
    userName user

This code doesn't compile, so I wrote those alternative version

userToText userId = do
    user <- runDB $ get404 userId
    listToJSON [user]


userToText userId = do
    (_,_,_,_,_,name,_,_) <- runDB $ get404 userId
    show name

All generate the same error

Handler/Report.hs:105:9:
Couldn't match expected type ‘HandlerT site IO b’
            with actual type ‘Text’
Relevant bindings include
  userToText :: Key PersistValue -> HandlerT site IO b
    (bound at Handler/Report.hs:102:1)
In a stmt of a 'do' block: listToJSON [user]
In the expression:
  do { user <- runDB $ get404 userId;
       listToJSON [user] }

thanks for the help


Solution

  • Your code is in the Handler monad, so your function needs to return something of the type Handler Text rather than just Text:

    userToText :: UserId -> Handler Text
    userToText userId = do
        user <- runDB $ get404 userId
        return $ userName user -- Note the `return` here
    

    (This is similar to how functions like getLine have type IO String rather than String).