AsyncTasks.purs 1.38 KB
Newer Older
1 2
module Gargantext.AsyncTasks where

3
import Data.Argonaut (decodeJson)
4
import Data.Argonaut.Parser (jsonParser)
5
import Data.Array as A
6 7 8 9 10 11 12 13 14
import Data.Either (Either(..))
import Data.Map as Map
import Data.Maybe (Maybe(..))
import DOM.Simple.Console (log2)
import Effect (Effect)
import Web.Storage.Storage as WSS

import Gargantext.Prelude
import Gargantext.Types as GT
15
import Gargantext.Utils as GU
16 17 18 19 20 21
import Gargantext.Utils.Reactix as R2


localStorageKey :: String
localStorageKey = "garg-async-tasks"

22 23 24
type Storage = Map.Map Int (Array GT.AsyncTaskWithType)

empty :: Storage
25 26
empty = Map.empty

27
getAsyncTasks :: Effect Storage
28 29 30 31 32 33 34 35 36
getAsyncTasks = R2.getls >>= WSS.getItem localStorageKey >>= handleMaybe
  where
    handleMaybe (Just val) = handleEither (parse val >>= decode)
    handleMaybe Nothing    = pure empty

    -- either parsing or decoding could fail, hence two errors
    handleEither (Left err) = err *> pure empty
    handleEither (Right ss) = pure ss

37 38
    parse  s = GU.mapLeft (log2 "Error parsing serialised sessions:") (jsonParser s)
    decode j = GU.mapLeft (log2 "Error decoding serialised sessions:") (decodeJson j)
39 40 41 42

removeTaskFromList :: Array GT.AsyncTaskWithType -> GT.AsyncTaskWithType -> Array GT.AsyncTaskWithType
removeTaskFromList ts (GT.AsyncTaskWithType { task: GT.AsyncTask { id: id' } }) =
  A.filter (\(GT.AsyncTaskWithType { task: GT.AsyncTask { id: id'' } }) -> id' /= id'') ts