From d6eb20dae23f6fe465a046a3b7e57d81f8811f8a Mon Sep 17 00:00:00 2001 From: Artyom Kazak Date: Tue, 16 Oct 2018 22:01:25 +0200 Subject: [PATCH] Invalidate cache in new handlers (#225) --- src/Guide/Api/Methods.hs | 28 +++++++++++++++++++++++----- 1 file changed, 23 insertions(+), 5 deletions(-) diff --git a/src/Guide/Api/Methods.hs b/src/Guide/Api/Methods.hs index 21f61ec..433a6a8 100644 --- a/src/Guide/Api/Methods.hs +++ b/src/Guide/Api/Methods.hs @@ -16,6 +16,7 @@ import Guide.Api.Types import Guide.State import Guide.Types import Guide.Utils +import Guide.Cache import qualified Data.Text as T import qualified Guide.Search as Search @@ -52,13 +53,14 @@ createCategory db title' group' = do Nothing -> do catId <- randomShortUid time <- liftIO getCurrentTime - (_edit, newCategory) <- dbUpdate db (AddCategory catId title' group' time) + (_edit, _newCategory) <- dbUpdate db (AddCategory catId title' group' time) + invalidateCache' db (CacheCategory catId) -- TODO addEdit edit - return (newCategory^.uid) + return catId -- | Delete a category. deleteCategory :: DB -> Uid Category -> Handler NoContent -deleteCategory db catId = do +deleteCategory db catId = uncache db (CacheCategory catId) $ do _mbEdit <- dbUpdate db (DeleteCategory catId) pure NoContent -- TODO mapM_ addEdit mbEdit @@ -83,6 +85,7 @@ createItem db catId name' = do kind' = if looksLikeLibrary then Library (Just name') else Other time <- liftIO getCurrentTime (_edit, _newItem) <- dbUpdate db (AddItem catId itemId name' time kind') + invalidateCache' db (CacheItem itemId) -- TODO: addEdit edit pure itemId @@ -90,7 +93,7 @@ createItem db catId name' = do -- | Delete an item. deleteItem :: DB -> Uid Item -> Handler NoContent -deleteItem db itemId = do +deleteItem db itemId = uncache db (CacheItem itemId) $ do _mbEdit <- dbUpdate db (DeleteItem itemId) pure NoContent -- TODO: mapM_ addEdit mbEdit @@ -103,7 +106,7 @@ deleteItem db itemId = do -- | Delete a trait (pro/con). deleteTrait :: DB -> Uid Item -> Uid Trait -> Handler NoContent -deleteTrait db itemId traitId = do +deleteTrait db itemId traitId = uncache db (CacheItemTraits itemId) $ do _mbEdit <- dbUpdate db (DeleteTrait itemId traitId) pure NoContent -- TODO: mapM_ addEdit mbEdit @@ -136,3 +139,18 @@ dbQuery :: (MonadIO m, EventState event ~ GlobalState, QueryEvent event) => DB -> event -> m (EventResult event) dbQuery db x = liftIO $ Acid.query db x + +-- Twins of corresponding functions used in "Guide.Handlers". +-- TODO: remove them when the old backend is gone. + +uncache :: (MonadIO m) => DB -> CacheKey -> m a -> m a +uncache db key act = do + gs <- dbQuery db GetGlobalState + x <- act + invalidateCache gs key + return x + +invalidateCache' :: (MonadIO m) => DB -> CacheKey -> m () +invalidateCache' db key = do + gs <- dbQuery db GetGlobalState + invalidateCache gs key