Last active
March 10, 2019 14:50
-
-
Save markosski/bd7b65fc11aed9f7d76e6a9b786cdd71 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
class UserService a where | |
getUser :: a -> Int -> IO User | |
updateUser :: a -> Int -> User -> IO User | |
instance UserService S3Config where | |
getUser = getUserS3 | |
updateUser = updateUserS3 | |
instance UserService DBConfig where | |
getUser = getUserDB | |
updateUser = updateUserDB | |
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) | |
-- different configs for UserServic | |
s3Config = S3Config "us-east-1" "bucketName" | |
dbConfig = DBConfig "somehost" 1234 | |
-- This is our program that may use different implementation of UserService | |
changeNameProgram :: UserService a => a -> Int -> String -> IO User | |
changeNameProgram conf uid newName = do | |
found <- getUser conf uid | |
updated <- updateUser conf uid found {name = newName} | |
return updated | |
res1 = changeNameProgram s3Config 10 "Melissa" | |
-- Getting user with S3 | |
-- Updating user with S3 | |
-- User {userId = Just 10, name = "Melissa", age = 37} | |
res2 = changeNameProgram dbConfig 20 "Frank" | |
-- Getting user with DB | |
-- Updating user with DB | |
-- User {userId = Just 20, name = "Frank", age = 37} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment