ebook-manager/src/Database/Book.hs

42 lines
1.3 KiB
Haskell
Raw Normal View History

2018-08-05 23:42:37 +03:00
{-# Language TypeApplications #-}
{-# Language DataKinds #-}
2018-08-07 23:25:21 +03:00
module Database.Book
( def
, insertBook
2018-08-08 21:58:36 +03:00
, InsertBook(..)
2018-08-07 23:25:21 +03:00
, usersBooks
, Book(..)
, BookID) where
2018-08-05 23:42:37 +03:00
import ClassyPrelude
import Database.Schema
import Database
import Database.Selda
2018-08-07 23:25:21 +03:00
import Database.Selda.Generic
2018-08-05 23:42:37 +03:00
2018-08-07 23:25:21 +03:00
usersBooks :: (MonadSelda m, MonadMask m, MonadIO m) => Username -> m [Book]
2018-08-05 23:42:37 +03:00
usersBooks username = fromRels <$> query q
where
q = do
userId :*: _ :*: username' :*: _ <- select (gen users)
2018-08-08 21:58:36 +03:00
book@(_ :*: _ :*: _ :*: _ :*: _ :*: owner) <- select (gen books)
2018-08-05 23:42:37 +03:00
restrict (username' .== literal username)
2018-08-08 21:58:36 +03:00
restrict (userId .== owner)
2018-08-05 23:42:37 +03:00
return book
2018-08-08 21:58:36 +03:00
data InsertBook = InsertBook { contentType :: Text
, title :: Maybe Text
, description :: Maybe Text
, owner :: Username }
2018-08-07 23:25:21 +03:00
-- Always inserts
2018-08-08 21:58:36 +03:00
insertBook :: (MonadSelda m, MonadMask m, MonadIO m) => InsertBook -> m (Maybe BookID)
insertBook InsertBook{..} = do
2018-08-07 23:25:21 +03:00
mUserId <- query $ do
userId :*: _ :*: username' :*: _ <- select (gen users)
2018-08-08 21:58:36 +03:00
restrict (username' .== literal owner)
2018-08-07 23:25:21 +03:00
return userId
forM (listToMaybe mUserId) $ \userId -> do
2018-08-08 21:58:36 +03:00
let book = Book{owner=userId,identifier=def,contentHash=Nothing,..}
BookID . fromRowId <$> insertGenWithPK books [book]