0

Sorry for newbie's question (and for my english) :)

I tries to write the following function:

  • the function downloads a content from URL1 (it's received as argument)
  • the function parses this content and extract URL2
  • the function downloads a content from URL2
  • the content from URL2 is a result of this function
  • if an error was occured, this function should return Nothing

I know how to execute the HTTP requests. I have a function to parse the request from URL1. But I don't know how:

  • to execute new request with extracted URL2
  • to ignore second request if URL2 isn't extracted (or error in URL1 is occured)
vasalvit
  • 143
  • 1
  • 4

2 Answers2

1

I principle you want something like this:

import Maybe
import Http

type Url = String
getContentFromUrl : Maybe Url -> Maybe String
getContentFromUrl url = --your implementation
extractUrlFromContent : Maybe String -> Maybe Url
extractUrlFromContent content = --your implementation
content = getContentFromUrl (Just "http://example.com") 
          |> extractUrlFromContent 
          |> getContentFromUrl
Christian
  • 6,242
  • 4
  • 28
  • 52
1

Sending an Http means talking to the outside world, which involves Signals in Elm. So the final result from URL2 will come packed in a Signal. As long as you're ok with that, you can use maybe to return the content of in a Maybe in a Signal. For example:

import Maybe
import Http

-- helper functions
isSuccess : Http.Response a -> Bool
isSuccess response = case response of
  Http.Success _ -> True
  _              -> False

responseToMaybe : Http.Response a -> Maybe.Maybe a
responseToMaybe response = case response of
  Http.Success a -> Just a
  _              -> Nothing

parseContentAndExtractUrl : String -> String
parseContentAndExtractUrl = identity -- this still requires your implementation

-- URL1
startUrl : String
startUrl = "www.example.com" -- replace this with your URL1

result1 : Signal (Http.Response String)
result1 = Http.sendGet <| constant startUrl

-- URL2
secondUrl : Signal String
secondUrl = result1
  |> keepIf isSuccess (Http.Success "")
  |> lift (\(Http.Success s) -> s)
  |> lift parseContentAndExtractUrl

result2 : Signal (Maybe String)
result2 = secondUrl
  |> Http.sendGet
  |> lift responseToMaybe

Note that there are plans to make all of this easier to work with: https://groups.google.com/d/topic/elm-discuss/BI0D2b-9Fig/discussion

Apanatshka
  • 5,882
  • 24
  • 35