LoginSignup
4
0

More than 1 year has passed since last update.

フロントエンドAPIライブラリKy

Last updated at Posted at 2023-04-18

概要

Kyは、HTTPリクエストを行うためのTypeScriptを使用したHTTPクライアントライブラリです。
AxiosFetchAPIといった他の一般的なライブラリと比べて、軽量で柔軟性の高いライブラリです。

最近そのライブラリのことを知って、エラー文言、ベースURLの設定、継承、通信リトライなど、色々便利なインターフェースが用意してあるようなので使ってみるきっかけになりました。

Kyの特徴:

  • JSONの自動解析とシリアル化
  • ヘッダーやクエリパラメータのカスタマイズ
  • 組み込みエラー処理

使用例

よく使用されているパターンをご紹介します。

// 基本リクエスト
async function getAllTodos() {
    const todos = await ky
        .get("https://jsonplaceholder.typicode.com/todos")
        .json();
    console.log(todos);
}
// 例外処理
async function getAllTodos() {
   try {
     const todos = await ky
        .get("https://jsonplaceholder.typicode.com/todos")
        .json();
     console.log(todos);
   } catch (error) {
     console.log(error.message);
   }
 }

ベースURLなどを指定するためのprefixUrlオプションが提供されています。

// prefixUrlを使用
async function getAllTodos() {
   try {
     const todos = await ky
        .get("todos", { prefixUrl: "https://jsonplaceholder.typicode.com" })
        .json();
     console.log(todos);
   } catch (error) {
     console.log(error.message);
   }
 }

createメソッドを使って、prefixUrlオプションやその他のカスタムオプションを持つKyクライアントのインスタンスを作成だきます。

// createを使用して前処理を入れる
const api = ky.create({
  prefixUrl: "https://jsonplaceholder.typicode.com"
});

async function getAllTodos() {
  try {
    const todos = await api.get("todos").json();
    console.log(todos);
  } catch (error) {
    console.log(error.message);
  }
}

extendメソッドを使用すると、元のインスタンスを継承しカスタムヘッダーなどの新しいオプションを追加したインスタンスを作れます。

// 拡張(継承)を使用
const secureApi = api.extend({
  headers: {
    Authorization: "token"
  }
});

結論

Kyは、JavaScriptとTypeScriptでHTTPリクエストを行うための強力で柔軟なライブラリです。シンプルで直感的なインターフェースを提供し、自動JSON解析など、多くの便利な機能を提供しています。フロントエンドのアプリを作る際、Kyを使えばHTTPリクエストを小工数で簡単に作成できます。

4
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
4
0