/docs/ja/03-processing.md

https://github.com/eed3si9n/gigahorse · Markdown · 89 lines · 65 code · 24 blank · 0 comment · 0 complexity · b306fb391d26710ead87484f9680f26e MD5 · raw file

  1. ---
  2. out:processing.html
  3. ---
  4. [concepts]: concepts.html
  5. Response の処理
  6. --------------
  7. `Request` 値が構築できたら次に `HttpClient` に渡して
  8. `run``download``processFull`, `runStream` といったメソッドを使って実行することができる
  9. ### http.run(r, f)
  10. `HttpClient` には多くのメソッドが定義されているがおそらく最も便利なのは
  11. `http.run(r, f)` メソッドだ[基本的な概念][concepts]のページで見たようにこれは
  12. `Request` 値と `FullResponse => A` の関数を受け取る
  13. Gigahorse `Future[String]` を返すために `Gigahorse.asString` という関数を提供するが
  14. これを拡張して他の型に応用できることは想像に難くない
  15. 一つ注意するべきなのは`run` メソッドは HTTP 2XX 番台のステータスのみを受け付け
  16. その他の場合は `Future` を失敗させるということだ(デフォルトの設定では3XX のリダイレクトは自動的に処理される)
  17. ### Future の後処理
  18. 関数を渡すのに加え中の値を map することで簡単に `Future` を後付けで処理することができる
  19. ```scala
  20. import gigahorse._, support.okhttp.Gigahorse
  21. import scala.concurrent._, duration._
  22. import ExecutionContext.Implicits._
  23. val http = Gigahorse.http(Gigahorse.config)
  24. val r = Gigahorse.url("https://api.duckduckgo.com").get.
  25. addQueryString(
  26. "q" -> "1 + 1"
  27. )
  28. val f0: Future[FullResponse] = http.run(r, identity)
  29. val f: Future[String] = f0 map { Gigahorse.asString andThen (_.take(60)) }
  30. Await.result(f, 120.seconds)
  31. ```
  32. `Future` に対して何らかの演算を行うときはimplicit な実行コンテキストが必要となる
  33. 実行コンテキストは`Future` のコールバックがどのスレッドプールで実行されるかを宣言するものだ
  34. 便宜上`Request` のみを受け取る `run` のオーバーロードもある
  35. ### FullResponse Either に持ち上げる
  36. `Future` が失敗する場合があるときによく行われる処理として内部の `A`
  37. `Either[Throwable, A]` に持ち上げるということが行われる
  38. <http://getstatuscode.com/> という便利なウェブサイトがあって、これは
  39. 任意の HTTP ステータスを返すことができる失敗した `Future` に対してブロックするとどうなるかをみてみよう
  40. ```scala
  41. val r = Gigahorse.url("http://getstatuscode.com/500")
  42. val f = http.run(r, Gigahorse.asString)
  43. Await.result(f, 120.seconds)
  44. ```
  45. `Gigahorse.asEither` という機構を使って `A` `Either[Throwable, A]` に持ち上げることができる
  46. ```scala
  47. val r = Gigahorse.url("http://getstatuscode.com/500")
  48. val f = http.run(r, Gigahorse.asEither)
  49. Await.result(f, 120.seconds)
  50. ```
  51. `asEither` は右バイアスのかかった `Either` として `map` することもできる
  52. ```scala
  53. val r = Gigahorse.url("http://getstatuscode.com/200")
  54. val f = http.run(r, Gigahorse.asEither map {
  55. Gigahorse.asString andThen (_.take(60)) })
  56. Await.result(f, 120.seconds)
  57. ```
  58. ### http.processFull(r, f)
  59. non-2XX レスポンスでエラーを投げたくなくて例えば 500 レスポンスのボディーテキストを
  60. 読み込みたい場合は `processFull` メソッドを使う
  61. ```scala
  62. val r = Gigahorse.url("http://getstatuscode.com/500")
  63. val f = http.processFull(r, Gigahorse.asString andThen (_.take(60)))
  64. Await.result(f, 120.seconds)
  65. ```