{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ForeignFunctionInterface #-}
{-# LANGUAGE LambdaCase #-}
module Miso.Effect.Storage
(
getLocalStorage
, getSessionStorage
, setLocalStorage
, setSessionStorage
, removeLocalStorage
, removeSessionStorage
, clearLocalStorage
, clearSessionStorage
, localStorageLength
, sessionStorageLength
) where
import Data.Aeson hiding (Object, String)
import GHCJS.Marshal
import GHCJS.Types
import Miso.FFI
import qualified Miso.FFI.Storage as Storage
import Miso.String
getStorageCommon
:: FromJSON b => (t -> JSM (Maybe JSVal)) -> t -> JSM (Either String b)
getStorageCommon f key = do
result :: Maybe JSVal <- f key
case result of
Nothing -> pure $ Left "Not Found"
Just v -> do
r <- parse v
pure $ case fromJSON r of
Success x -> Right x
Error y -> Left y
getSessionStorage :: FromJSON model => MisoString -> JSM (Either String model)
getSessionStorage =
getStorageCommon $ \t -> do
s <- Storage.sessionStorage
r <- Storage.getItem s t
fromJSVal r
getLocalStorage :: FromJSON model => MisoString -> JSM (Either String model)
getLocalStorage = getStorageCommon $ \t -> do
s <- Storage.localStorage
r <- Storage.getItem s t
fromJSVal r
setLocalStorage :: ToJSON model => MisoString -> model -> JSM ()
setLocalStorage key model = do
s <- Storage.localStorage
Storage.setItem s key =<< stringify model
setSessionStorage :: ToJSON model => MisoString -> model -> JSM ()
setSessionStorage key model = do
s <- Storage.sessionStorage
Storage.setItem s key =<< stringify model
removeLocalStorage :: MisoString -> JSM ()
removeLocalStorage key = do
s <- Storage.localStorage
Storage.removeItem s key
removeSessionStorage :: MisoString -> JSM ()
removeSessionStorage key = do
s <- Storage.sessionStorage
Storage.removeItem s key
clearLocalStorage :: JSM ()
clearLocalStorage = Storage.clear =<< Storage.localStorage
clearSessionStorage :: JSM ()
clearSessionStorage = Storage.clear =<< Storage.sessionStorage
localStorageLength :: JSM Int
localStorageLength = Storage.length =<< Storage.localStorage
sessionStorageLength :: JSM Int
sessionStorageLength = Storage.length =<< Storage.sessionStorage