LinkedIn.purs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. module LinkedIn (APIError(..), encodeToJson, getContext, extractFromDocument, extractFromDocumentInContext) where
  2. import Prelude
  3. import Control.Monad.Except (ExceptT, lift, runExceptT, throwError, withExceptT)
  4. import Data.Argonaut.Core (Json)
  5. import Data.Argonaut.Encode (class EncodeJson, encodeJson)
  6. import Data.Argonaut.Encode.Generic (genericEncodeJson)
  7. import Data.Either (Either(..))
  8. import Data.Generic.Rep (class Generic)
  9. import Data.Maybe (Maybe(..))
  10. import Data.Show.Generic (genericShow)
  11. import Effect (Effect)
  12. import LinkedIn.Output (OutputError, toOutput)
  13. import LinkedIn.Output.Types (Output)
  14. import LinkedIn.PageUrl (PageUrl, pageUrlP)
  15. import Parsing (runParser)
  16. import Web.DOM (Document)
  17. import Web.DOM.Document (url)
  18. import Web.URL as U
  19. data APIError =
  20. ErrorExtraction OutputError
  21. | ErrorInvalidUrl
  22. | ErrorUnexpectedUrl
  23. derive instance Generic APIError _
  24. instance Show APIError where
  25. show = genericShow
  26. instance EncodeJson APIError where
  27. encodeJson a = genericEncodeJson a
  28. getContext ∷ Document → Effect (Either APIError PageUrl)
  29. getContext = runExceptT <<< getContext'
  30. getContext' ∷ Document → ExceptT APIError Effect PageUrl
  31. getContext' dom = do
  32. u <- lift $ url dom
  33. case U.fromAbsolute u of
  34. Nothing -> throwError ErrorInvalidUrl
  35. Just u' -> case runParser (U.pathname u') pageUrlP of
  36. Left _ -> throwError ErrorUnexpectedUrl
  37. Right page -> pure page
  38. extractFromDocument :: Document -> Effect (Either APIError Output)
  39. extractFromDocument = runExceptT <<< extractFromDocument'
  40. extractFromDocument' ∷ Document → ExceptT APIError Effect Output
  41. extractFromDocument' dom = do
  42. ctx <- getContext' dom
  43. toOutput' ctx dom
  44. extractFromDocumentInContext :: PageUrl -> Document -> Effect (Either APIError Output)
  45. extractFromDocumentInContext url dom = runExceptT $ toOutput' url dom
  46. toOutput' ∷ PageUrl → Document → ExceptT APIError Effect Output
  47. toOutput' ctx dom = withExceptT (\err -> ErrorExtraction err) $ toOutput ctx dom
  48. encodeToJson :: Either String Output -> Json
  49. encodeToJson = encodeJson