module Haste.LocalStorage (setItem, getItem, removeItem) where
import Haste
import Haste.Foreign
import Haste.Serialize
import Haste.JSON
import Control.Applicative
setItem :: Serialize a => String -> a -> IO ()
setItem k = store k . encodeJSON . toJSON
where
store :: String -> JSString -> IO ()
store = ffi "(function(k,v) {localStorage.setItem(k,v);})"
getItem :: Serialize a => String -> IO (Either String a)
getItem k = do
maybe (Left "No such value") (\s -> decodeJSON s >>= fromJSON) <$> load k
where
load :: String -> IO (Maybe JSString)
load = ffi "(function(k) {return localStorage.getItem(k);})"
removeItem :: String -> IO ()
removeItem = ffi "(function(k) {localStorage.removeItem(k);})"