📖

もうAxiosで消耗しない!npm初心者が作った「axios-fluent」が解決する3つの面倒

に公開

はじめに

HTTPリクエストを書くたびに、こんな経験ありませんか?

// 設定が複雑すぎる...
const response = await axios.post('https://api.example.com/users', data, {
  headers: {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${token}`
  },
  timeout: 5000,
  httpsAgent: new https.Agent({
    rejectUnauthorized: false  // 自己署名証明書エラーで毎回これを書く...
  })
});
const user = response.data;  // なんで毎回 .data 書かなあかんねん
// エラーハンドリングが地獄
try {
  await axios.get('/api/data');
} catch (error) {
  // error.response?.data?.message? error.response?.status? error.config?.url?
  // どこに何があるか毎回ドキュメント見に行く...
  console.log('Status:', error.response?.status);
  console.log('Message:', error.response?.data?.message);
  console.log('URL:', error.config?.url);
}

そんな開発者の悩みを解決するために、axios-fluentを作りました。これは私が初めて公開したnpmパッケージですが、実際のプロジェクトで感じた「Axiosのここが面倒」を全部詰め込んだ実用ライブラリです。

npm install axios-fluent

https://www.npmjs.com/package/axios-fluent

🎯 axios-fluentが解決する3つの課題

1. リクエスト構築が複雑 → ビルダースタイルでスッキリ

Before (素のAxios)

const config = {
  baseURL: 'https://api.example.com',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${token}`
  },
  timeout: 10000
};

const instance = axios.create(config);
const response = await instance.get('/users/1');
const user = response.data;

After (axios-fluent)

const client = Axon.new()
  .baseUrl('https://api.example.com')
  .bearer(token)
  .json()
  .timeout(10000);

const user = await client.get('/users/1').data();

💡 技術ポイント:Immutableビルダーパターン

axios-fluentの各メソッドは新しいインスタンスを返す設計になってます。

src/Axon.ts
public bearer(token: string): Axon {
  const newConfig = {
    ...this.config,
    headers: { ...this.config.headers, Authorization: `Bearer ${token}` },
  };
  return new Axon(newConfig, this.instance);  // 新しいインスタンスを返す
}

これにより:

  • メソッドチェーンが自然に書ける
  • 元のインスタンスが汚染されない(副作用なし)
  • 関数型プログラミングの原則に従った設計

2. Axiosのエラーが冗長すぎる → AxonErrorで必要な情報だけ

Before (素のAxios)

try {
  await axios.get('/api/users');
} catch (error) {
  // 必要な情報がバラバラの場所にある...
  const status = error.response?.status;
  const message = error.response?.data?.message;
  const url = error.config?.url;
  const method = error.config?.method;

  console.log(`${method} ${url} failed with ${status}: ${message}`);
  // これ毎回書くの面倒すぎる
}

After (axios-fluent)

try {
  await client.get('/api/users');
} catch (error) {
  if (error instanceof AxonError) {
    console.log(error.toString());
    // ↓ これが自動で整形されて出力される
    // AxonError: Request failed with status code 404
    //   Request: GET https://api.example.com/api/users
    //   Status: 404 Not Found
    //   Response: {"error":"User not found"}
  }
}

💡 技術ポイント:本当に必要な5つのプロパティだけ

src/Axon.ts
export class AxonError extends Error {
  public readonly status?: number;         // HTTPステータスコード
  public readonly statusText?: string;     // ステータステキスト
  public readonly url?: string;            // リクエストURL
  public readonly method?: string;         // HTTPメソッド
  public readonly responseData?: any;      // レスポンスボディ

  public toString(): string {
    const parts = [`AxonError: ${this.message}`];
    if (this.method && this.url) {
      parts.push(`  Request: ${this.method} ${this.url}`);
    }
    if (this.status) {
      parts.push(`  Status: ${this.status} ${this.statusText || ''}`);
    }
    if (this.responseData) {
      parts.push(`  Response: ${JSON.stringify(this.responseData)}`);
    }
    return parts.join('\n');
  }
}

v2.0.0で不要なプロパティ(headers、originalError)を削除し、デバッグに本当に必要な情報だけに絞りました。

3. 自己署名証明書エラーの悪夢 → allowInsecureが味方

開発環境でHTTPSの自己署名証明書使ってると、毎回これ書くことになりますよね。

Before (素のAxios)

const https = require('https');

const instance = axios.create({
  httpsAgent: new https.Agent({
    rejectUnauthorized: false  // 開発環境のたびにこれコピペ...
  })
});

After (axios-fluent)

// 開発環境用の便利ファクトリー
const client = Axon.dev();

// または明示的に指定
const client = Axon.new({ allowInsecure: true });

💡 技術ポイント:セキュアがデフォルト、開発は楽に

src/Axon.ts
public static new(options: Options = { allowInsecure: false }) {
  const config: AxiosRequestConfig = {};

  if (options?.allowInsecure) {
    config.httpsAgent = new https.Agent({
      rejectUnauthorized: false,  // 明示的にオプトインした時だけ無効化
    });
  }

  return new Axon(config);
}

public static dev() {
  return Axon.new({ allowInsecure: true });  // 開発用ショートカット
}

セキュリティファースト設計:

  • デフォルトは証明書検証有効(本番環境で安全)
  • allowInsecureで明示的にオプトイン必要
  • Axon.dev()は開発時の便利ツール(名前で用途が明確)

📦 実践的な使い方

API クライアントラッパーを作る

src/services/api-client.ts
import { Axon } from 'axios-fluent';

class ApiClient {
  private client: Axon;

  constructor(baseUrl: string, token?: string) {
    this.client = Axon.new()
      .baseUrl(baseUrl)
      .json()
      .timeout(10000);

    if (token) {
      this.client = this.client.bearer(token);
    }
  }

  async getUser(id: number): Promise<User> {
    return await this.client.get<User>(`/users/${id}`).data();
  }

  async createUser(data: CreateUserDto): Promise<User> {
    return await this.client.post<User>('/users', data).data();
  }

  async uploadAvatar(userId: number, file: File): Promise<void> {
    const formData = new FormData();
    formData.append('avatar', file);

    await this.client
      .multipart()
      .post(`/users/${userId}/avatar`, formData);
  }
}

export const api = new ApiClient(
  process.env.API_URL || 'https://api.example.com',
  localStorage.getItem('authToken') || undefined
);

レスポンス便利メソッドで冗長なコードを削減

// Before: 毎回 .data を書く
const response = await axios.get<User>('/users/1');
const user = response.data;
const status = response.status;

// After: 欲しいものを直接取得
const user = await client.get<User>('/users/1').data();
const status = await client.get('/users/1').status();
const isOk = await client.post('/users', data).ok();  // 2xxかどうか判定

💡 技術ポイント:PromiseLikeで後方互換性維持

src/Axon.ts
export class AxonResponse<T = any> implements PromiseLike<AxiosResponse<T>> {
  async data(): Promise<T> {
    const response = await this.responsePromise;
    return response.data;
  }

  async status(): Promise<number> {
    const response = await this.responsePromise;
    return response.status;
  }

  async ok(): Promise<boolean> {
    const response = await this.responsePromise;
    return response.status >= 200 && response.status < 300;
  }

  // 後方互換性のためにPromiseインターフェースも実装
  then<TResult1 = AxiosResponse<T>, TResult2 = never>(
    onfulfilled?: ((value: AxiosResponse<T>) => TResult1 | PromiseLike<TResult1>) | null,
    onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null
  ): PromiseLike<TResult1 | TResult2> {
    return this.responsePromise.then(onfulfilled, onrejected);
  }
}

既存コードを壊さず、新機能を追加できる設計です。

エラーハンドリングのベストプラクティス

import { AxonError } from 'axios-fluent';

async function fetchUserWithRetry(id: number, maxRetries = 3): Promise<User> {
  for (let attempt = 1; attempt <= maxRetries; attempt++) {
    try {
      return await client.get<User>(`/users/${id}`).data();
    } catch (error) {
      if (error instanceof AxonError) {
        // ステータスコードで処理を分岐
        if (error.status === 404) {
          throw new Error(`User ${id} not found`);
        }

        if (error.status && error.status >= 500) {
          // サーバーエラーはリトライ
          if (attempt === maxRetries) {
            throw new Error(`Server error after ${maxRetries} attempts: ${error.toString()}`);
          }
          await sleep(1000 * attempt);  // Exponential backoff
          continue;
        }

        // 4xx系はリトライしない
        throw error;
      }

      // AxonError以外(ネットワークエラーなど)
      throw error;
    }
  }

  throw new Error('Unexpected error in retry logic');
}

認証フローの実装

class AuthService {
  private client: Axon;
  private refreshToken?: string;

  constructor(baseUrl: string) {
    this.client = Axon.new().baseUrl(baseUrl).json();
  }

  async login(email: string, password: string): Promise<void> {
    const response = await this.client
      .post<AuthResponse>('/auth/login', { email, password })
      .data();

    this.refreshToken = response.refreshToken;
    this.client = this.client.bearer(response.accessToken);
  }

  async refreshAccessToken(): Promise<void> {
    if (!this.refreshToken) {
      throw new Error('No refresh token available');
    }

    const response = await this.client
      .post<AuthResponse>('/auth/refresh', { refreshToken: this.refreshToken })
      .data();

    this.refreshToken = response.refreshToken;
    this.client = this.client.bearer(response.accessToken);
  }

  async fetchProtectedResource<T>(url: string): Promise<T> {
    try {
      return await this.client.get<T>(url).data();
    } catch (error) {
      if (error instanceof AxonError && error.status === 401) {
        // トークン期限切れ → リフレッシュしてリトライ
        await this.refreshAccessToken();
        return await this.client.get<T>(url).data();
      }
      throw error;
    }
  }
}

🚀 なぜaxios-fluentが必要なのか

1. 開発速度が上がる

  • ビルダーパターンでリクエスト設定が直感的
  • レスポンス便利メソッドで冗長なコード削減
  • エラーハンドリングがシンプルに

2. コードの可読性が向上

// Before: ネストが深い
const response = await axios.post(
  'https://api.example.com/users',
  data,
  {
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${token}`
    },
    timeout: 5000
  }
);

// After: フラットで読みやすい
const user = await Axon.new()
  .baseUrl('https://api.example.com')
  .bearer(token)
  .json()
  .timeout(5000)
  .post('/users', data)
  .data();

3. 型安全性が保たれる

interface User {
  id: number;
  name: string;
  email: string;
}

// TypeScriptの型推論がフル活用できる
const user: User = await client.get<User>('/users/1').data();
//    ^? User型として推論される

4. プロダクション対応

  • デフォルトでセキュア(HTTPS証明書検証ON)
  • 開発環境の利便性も確保(Axon.dev())
  • エラーハンドリングが体系的
  • 100%後方互換性(既存コードを壊さない)

📊 パフォーマンス&バンドルサイズ

axios-fluentはAxiosのラッパーなので、パフォーマンスオーバーヘッドはほぼゼロです。

項目 値
パッケージサイズ ~17KB (minified)
依存関係 axios (peer), form-data
TypeScript対応 ✅ フル対応
Node.js対応 v20+

まとめ

axios-fluentは、私が初めて公開したnpmパッケージですが、実際の開発現場で感じた痛みを解決するために設計しました。

✅ 3つの主要な改善点

  1. ビルダーパターンでリクエスト構築が簡単に
  2. AxonErrorでエラーハンドリングが直感的に
  3. allowInsecureで開発環境の証明書エラーから解放

✅ 実用性重視の設計

  • セキュアがデフォルト、開発時は便利に
  • 後方互換性100%(既存コードを壊さない)
  • TypeScript型安全性を保持
  • 実践的なサンプルコード6種類を提供

もしあなたが「Axiosの設定が複雑」「エラーハンドリングが面倒」「自己署名証明書で毎回エラー」と感じているなら、ぜひ試してみてください。

npm install axios-fluent

📦 NPM: https://www.npmjs.com/package/axios-fluent
📂 GitHub: https://github.com/oharu121/axios-fluent

フィードバックやコントリビューションも大歓迎です!

Discussion