Guest User

Untitled

a guest
Nov 19th, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.76 KB | None | 0 0
  1. storeEntity :: (Entity a) => a -> IO ()
  2. retrieveEntity :: (Entity a) => Integer -> IO a
  3. publishEntity :: (Entity a) => a -> IO ()
  4.  
  5. main = do
  6. let user1 = User 1 "Thomas" "Meier" "tm@meier.com"
  7. storeEntity user1
  8. user2 <- retrieveEntity 1 :: IO User -- how to avoid this type annotation?
  9. publishEntity user2
  10.  
  11. {-# LANGUAGE DeriveGeneric, DeriveAnyClass #-}
  12. module Example where
  13. import GHC.Generics
  14. import Data.Aeson
  15.  
  16. -- | Entity type class
  17. class (ToJSON e, FromJSON e, Eq e, Show e) => Entity e where
  18. getId :: e -> Integer
  19.  
  20. -- | a user entity
  21. data User = User {
  22. userId :: Integer
  23. , firstName :: String
  24. , lastName :: String
  25. , email :: String
  26. } deriving (Show, Eq, Generic, ToJSON, FromJSON)
  27.  
  28. instance Entity User where
  29. getId = userId
  30.  
  31.  
  32. -- | load persistent entity of type a and identified by id
  33. retrieveEntity :: (Entity a) => Integer -> IO a
  34. retrieveEntity id = do
  35. -- compute file path based on id
  36. let jsonFileName = getPath id
  37. -- parse entity from JSON file
  38. eitherEntity <- eitherDecodeFileStrict jsonFileName
  39. case eitherEntity of
  40. Left msg -> fail msg
  41. Right e -> return e
  42.  
  43. -- | store persistent entity of type a to a json file
  44. storeEntity :: (Entity a) => a -> IO ()
  45. storeEntity entity = do
  46. -- compute file path based on entity id
  47. let jsonFileName = getPath (getId entity)
  48. -- serialize entity as JSON and write to file
  49. encodeFile jsonFileName entity
  50.  
  51. -- | compute path of data file based on id
  52. getPath :: Integer -> String
  53. getPath id = ".stack-work/" ++ show id ++ ".json"
  54.  
  55. publishEntity :: (Entity a) => a -> IO ()
  56. publishEntity = print
  57.  
  58. main = do
  59. let user1 = User 1 "Thomas" "Meier" "tm@meier.com"
  60. storeEntity user1
  61. user2 <- retrieveEntity 1 :: IO User
  62. print user2
Add Comment
Please, Sign In to add comment