0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

🍛🍛🍛🍛🍛APIはカレーでラッピングするが吉🍛🍛🍛🍛🍛

Posted at

例えばAPIを呼び出す関数を書くとき。
以下のように感じに書くこともできます。

const base_url = "https://example.com"
const async callAPI = (endpoint="normal",count=10, q="Excel") => {
  const url = `${base_url}/${endpoint}?q=${q}&count=${count}`
  const response = await fetch(url)
  return response.json()
}

ですが、urlを切り替えたいときにbase_urlを変更するのはなんだか癪ですよね。
そこで別の選択肢としてカレー化を使ってみましょう。

// カリー化
const async curreyCallAPI = (base_url = "https://example.com") => {
  return (endpoint="normal",count=10, q="Excel") => {
    const url = `${base_url}/${endpoint}?q=${q}&count=${count}`
    const response = await fetch(url)
    return response.json()
  }
}

// 適応
if is_dev === true:
    const callAPIDokomo  = curreyCallAPI("https://dokomo.com")
else:
    const callAPI        = curreyCallAPI()

このようにカレー化を使用することで以下の二つのメリットがあります。

  • 中身の処理が似ているが微妙に内容が異なる処理の重複を防ぐ
  • 関数の中身の決定を遅らせる
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?