I'm new to Haskell so apologies in advance for the potentially stupid question.
I'd like to build a data structure that is constructed from two http requests in my application.
My first request gets a basic list of users which I could choose to decode
to Maybe [User]
r <- getWith opts "https://www.example.com/users"
let users = decode $ r ^. responseBody :: Maybe [User]
But if I'd like to enrich my user data by calling a second endpoint for each of the users that respond by doing something like
r2 <- getWth opts "https://www.example.com/users/{userid}/addresses"
let enrichedUser = decode $ r2 ^. responseBody :: Maybe EnrichedUser
I can't quite piece these parts together at the minute. I'm in a do
block thats expecting an IO ()
Any help would be appreciated!
I'm assuming that the type of
enrichedUser
is supposed to beMaybe EnrichedUser
and notMaybe [EnrichedUser]
, right?If so, after extracting the
[User]
list fromusers :: Maybe [User]
, the problem you're facing is running a monadic action (to fetch the web page) for eachUser
. There's a handy combinator for this inControl.Monad
:which can be specialized in your situation to:
This says, if you know how to write a function that takes a
User
and creates an IO action that will create anEnrichedUser
, you can usemapM
to turn this into a function that takes a list[User]
and creates an IO action to create a whole list[EnrichedUser]
.In your application, I imagine the former function would look something like:
and then you can write (in your IO do-block):
I've omitted the
Maybe
processing here for simplicity. If enriching fails, you probably want to somehow coerce a regularUser
into a defaultEnrichedUser
anyway, so you'd modify the bottom of theenrich
function to read:and everything else would stay the same.