Search code examples
haskellyesodpersist

getBy404 vs get404


I'm trying to build a rest service using the Yesod web framework. I can get entries by Id but I cannot get them by unique key. It's because the types signature of getBy404 is different to get404. getBy404 returns the value wrapped in a Entity and get404 returns the pure value.

module Handler.MusicaUser where
import Import

getMusicaUserR :: MusicaUserId -> Handler Value
getMusicaUserR pid = do
post <- runDB $ get404 pid

    return $ object ["user" .= (Entity pid post)]

putMusicaUserR :: MusicaUserId -> Handler Value
putMusicaUserR pid = do
    post <- requireJsonBody :: Handler MusicaUser

    runDB $ replace pid post

    sendResponseStatus status200 ("UPDATED" :: Text)

deleteMusicaUserR :: MusicaUserId -> Handler Value
deleteMusicaUserR pid = do
    runDB $ delete pid

    sendResponseStatus status200 ("DELETED" :: Text)

I have tried modifying my code using this example

Why does this code work with Yesod.Persist's get404 but not getBy404?

Thank. I appreciate your help.

EDIT

I think I'm getting closer

getMusicaUserR :: Int64 -> Handler Value
getMusicaUserR facebookId = do
   user <- runDB $ getBy404 (UniqueFacebookId facebookId)
   return $ object ["user" .= (user)]

The error I get now is

Application.hs:41:1:
    Couldn't match type ‘Int64’ with ‘Key MusicaUser’
    Expected type: MusicaUserId
      Actual type: Int64
    In the first argument of ‘MusicaUserR’, namely ‘dyn_al6K’
    In the first argument of ‘Just’, namely ‘MusicaUserR dyn_al6K’

Is Int64 the correct type for my function. The reason I used it is because that is how facebookId is defined in my model. I have also tried using UniqueFacebookId.

To fix the above error I needed to change my routes definitions to

/users/#Int64 instead of /users/MusicaUserId


Solution

  • When you look at the definition of Entity, you can see that it is just a container for an entity and it's key. You can use the two functions entityKey and entityVal to extract the key and the value from the return value of getBy404.