Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- storeEntity :: (Entity a) => a -> IO ()
- retrieveEntity :: (Entity a) => Integer -> IO a
- publishEntity :: (Entity a) => a -> IO ()
- main = do
- let user1 = User 1 "Thomas" "Meier" "tm@meier.com"
- storeEntity user1
- user2 <- retrieveEntity 1 :: IO User -- how to avoid this type annotation?
- publishEntity user2
- {-# LANGUAGE DeriveGeneric, DeriveAnyClass #-}
- module Example where
- import GHC.Generics
- import Data.Aeson
- -- | Entity type class
- class (ToJSON e, FromJSON e, Eq e, Show e) => Entity e where
- getId :: e -> Integer
- -- | a user entity
- data User = User {
- userId :: Integer
- , firstName :: String
- , lastName :: String
- , email :: String
- } deriving (Show, Eq, Generic, ToJSON, FromJSON)
- instance Entity User where
- getId = userId
- -- | load persistent entity of type a and identified by id
- retrieveEntity :: (Entity a) => Integer -> IO a
- retrieveEntity id = do
- -- compute file path based on id
- let jsonFileName = getPath id
- -- parse entity from JSON file
- eitherEntity <- eitherDecodeFileStrict jsonFileName
- case eitherEntity of
- Left msg -> fail msg
- Right e -> return e
- -- | store persistent entity of type a to a json file
- storeEntity :: (Entity a) => a -> IO ()
- storeEntity entity = do
- -- compute file path based on entity id
- let jsonFileName = getPath (getId entity)
- -- serialize entity as JSON and write to file
- encodeFile jsonFileName entity
- -- | compute path of data file based on id
- getPath :: Integer -> String
- getPath id = ".stack-work/" ++ show id ++ ".json"
- publishEntity :: (Entity a) => a -> IO ()
- publishEntity = print
- main = do
- let user1 = User 1 "Thomas" "Meier" "tm@meier.com"
- storeEntity user1
- user2 <- retrieveEntity 1 :: IO User
- print user2
Add Comment
Please, Sign In to add comment