Skip to content

Instantly share code, notes, and snippets.

@markosski
Last active March 10, 2019 15:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save markosski/f8b944b4c9ee085b165825071e224324 to your computer and use it in GitHub Desktop.
Save markosski/f8b944b4c9ee085b165825071e224324 to your computer and use it in GitHub Desktop.
import Data.Maybe
data User = User {
userId :: Maybe Int,
name :: String,
age :: Int
} deriving (Show)
data S3Config = S3Config {
region :: String,
bucket :: String
} deriving (Show)
data DBConfig = DBConfig {
host :: String,
port :: Int
}
data UserService = UserService {
getUser :: Int -> IO User,
updateUser :: Int -> User -> IO User
}
s3Config = S3Config "us-east-1" "bucketName"
dbConfig = DBConfig "somehost" 1234
getUserS3 :: S3Config -> Int -> IO User
getUserS3 conf uid = do
putStrLn "Getting user using S3"
return $ User (Just uid) "Some Name" 37
updateUserS3 :: S3Config -> Int -> User -> IO User
updateUserS3 conf uid user = do
putStrLn "Updating user using S3"
return $ User (Just uid) (name user) (age user)
getUserDB :: DBConfig -> Int -> IO User
getUserDB conf uid = do
putStrLn "Getting user using DB"
return $ User (Just uid) "Some Name" 37
updateUserDB :: DBConfig -> Int -> User -> IO User
updateUserDB conf uid user = do
putStrLn "Updating user using DB"
return $ User (Just uid) (name user) (age user)
getUserMem :: Int -> IO User
getUserMem uid = do
putStrLn "Getting user using Mem"
return $ User (Just uid) "Some Name" 37
updateUserMem :: Int -> User -> IO User
updateUserMem uid user = do
putStrLn "Updating user using Mem"
return $ User (Just uid) (name user) (age user)
s3Service = UserService (getUserS3 s3Config) (updateUserS3 s3Config)
dbService = UserService (getUserDB dbConfig) (updateUserDB dbConfig)
memService = UserService getUserMem updateUserMem
-- This is our program that may use different implementation of UserService
changeNameProgram :: UserService -> Int -> String -> IO User
changeNameProgram uService uid newName = do
found <- getUser uService uid
updated <- updateUser uService uid (found {name = newName})
return updated
res1 = changeNameProgram s3Service 10 "Melissa S3"
res2 = changeNameProgram dbService 10 "Melissa DB"
res3 = changeNameProgram memService 10 "Melissa Mem"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment