1

使用servantpersistent库创建 REST API,我在使用insertUnique创建新实体时遇到类型不匹配错误。

这是有问题的功能:

createUser :: Entity User -> App Int64
createUser p = do
    maybeNewUser <- runDb (insertUnique (User (userUsername $ entityVal p) (userSpotifyUser $ entityVal p)))
    case maybeNewUser of
        Nothing -> throwError err400
        Just newUser -> return $ fromSqlKey newUser

出现以下错误:

Couldn't match expected type ‘persistent-2.2.4.1:Database.Persist.Sql.Types.SqlBackend’
        with actual type ‘persistent-2.2.4.1:Database.Persist.Class.PersistEntity.PersistEntityBackend
                            (String
                             -> String
                             -> time-1.5.0.1:Data.Time.Clock.UTC.UTCTime
                             -> time-1.5.0.1:Data.Time.Clock.UTC.UTCTime
                             -> User)’
In the first argument of ‘runDb’, namely
[snip]

供参考,runDb功能:

runDb :: (MonadReader Config m, MonadIO m) => SqlPersistT IO b -> m b
runDb query = do
    pool <- asks getPool
    liftIO $ runSqlPool query pool

和新App类型:

newtype App a = App
    { runApp :: ReaderT Config (ExceptT ServantErr IO) a } deriving
        (Functor, Applicative, Monad, MonadReader Config, MonadError ServantErr, MonadIO)

我尝试过类型提示insertUniqueas的结果SqlBackend,但这会导致同样令人困惑的错误。SqlBackendPersistentEntityBackend类型不能互换吗?

或者单子格式不正确?

非常感谢任何帮助。

4

1 回答 1

1

在这个答案的帮助下,我能够弄清楚。

get和其他人一样,insertUnique在这种情况下返回普通User而不是Entity User.

createUser :: User -> App Int64
createUser p = do
    user <- (User (userUsername $ entityVal p) (userSpotifyUser $ entityVal p))
    let insertUser = insertUnique user :: SqlPersistT IO (Maybe (Key User))
    maybeNewUserKey <- runDb insertUser
    case maybeNewUserKey of
        Nothing -> throwError err400
        Just newUserKey ->
            return $ fromSqlKey newUserKey

事后看来更有意义,因为runDb接受了SqlPersistT转换后的单子。

于 2016-11-23T06:07:39.573 回答