1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 | module Repos.Stories ( create , get , getAll , createIO , lastMonth , lastStories) where import Database.SQLite.Simple.QQ import Data.Text (Text) import Repos.Utils import Types import Models import Utils import Database.SQLite.Simple (Only(..)) import qualified Database.SQLite.Simple as SQL import Data.Maybe (fromMaybe) get :: (CanDB m, HasAuth m) => Text -> m (Maybe Story) get sId = do userId <- getAuthUserId toMaybe <$> query [sql| select id, prompt_id, user_id, title, summary, story, created_at from stories where id = (?) and user_id = (?) |] (sId, userId) getAll :: (CanDB m, HasAuth m) => m [Story] getAll = do userId <- getAuthUserId query [sql| select id, prompt_id, user_id, title, summary, story, created_at from stories where user_id = (?) |] (Only userId) lastStories :: (CanDB m, HasUser m) => Int -> m [Story] lastStories num = do mUserId <- getUserId case mUserId of Nothing -> return [] Just userId -> do query [sql| select id, prompt_id, user_id, title, summary, story, created_at from stories where user_id = (?) order by created_at desc limit (?) |] (userId, num) lastMonth :: (CanDB m, HasAuth m) => m StoriesLimit lastMonth = do userId <- getAuthUserId limit <- toMaybe <$> query [sql| select count(*) from stories where user_id = (?) and created_at > datetime('now', '-30 days') |] (Only userId) return $ fromMaybe (StoriesLimit 0) limit create :: (CanDB m, HasAuth m) => Text -> Text -> Text -> Text -> Text -> m DbR create sId pId title summary story = do userId <- getAuthUserId execute [sql| insert into stories(id, prompt_id, user_id, title, summary, story, created_at) values (?, ?, ?, ?, ?, ?, datetime()) |] (sId, pId, userId, title, summary, story) createIO :: Text -> Text -> Text -> Text -> Text -> Text -> SQL.Connection -> IO () createIO sId pId userId title summary story conn = do SQL.execute conn [sql| insert into stories(id, prompt_id, user_id, title, summary, story, created_at) values (?, ?, ?, ?, ?, ?, datetime()) |] (sId, pId, userId, title, summary, story) |