本文へスキップ
Skillpedia
WebサイトとUI(フロントエンド)7.8k · #13048

data-service-optional-params

できること

このスキルは、AIエージェントが、オプションのフィルターを受け付けるダッシュボードのデータサービスを書くよう導きます。APIの呼び出しに、一部のパラメーターだけが必要な開発者向けです。

使う場面

  • ✓オプションのフィルターがあり、値が設定されたときだけ追加すべきAPI呼び出しのとき。
  • ✓ダッシュボードのパネルが、サーキットブレーカーで堅牢に取得する必要があるとき。
  • ✓手作業で文字列を連結せず、きれいなクエリ文字列を作りたいとき。

スキルのリンク

https://github.com/HKUDS/AgentPilot/blob/main/openspace/legacy/v1/showcase/skills/data-service-optional-params/SKILL.md

コピーしてAI(Claude、ChatGPT、Cursor)に貼り付け、指示に従うよう頼んでください。

使い方

いちばん簡単な方法:メッセージをコピーしてAIに貼り付けるだけ。AIがスキルを読んで指示に従います。

貼り付け用メッセージ

このスキルを使って手伝ってください:https://github.com/HKUDS/AgentPilot/blob/main/openspace/legacy/v1/showcase/skills/data-service-optional-params/SKILL.md このリンクのSKILL.mdファイルを読んで、私の作業でその指示に従ってください。
こういうスキルを、AIが自分で見つけてくれたら?無料のSkillpedia MCPをインストール。1行で、作業の前に15,000+のスキルから探してくれます。1分でインストール →

AIへの頼み方の例

“ニュースパネル用のデータサービスを、サーキットブレーカー付きで書いてください。国とカテゴリーのフィルターはオプションにしてください。”

毎週5つの新しいスキル。1分で読めます。

仕組み

エージェントは、URLSearchParamsでクエリ文字列を作り、値があるフィルターだけを追加します。その後、サービスはリクエストをサーキットブレーカーを通して送り、結果をパネル用にキャッシュします。

技術的な内容(元のSKILL.md)

作者による元のテキスト(英語)をGitHubからそのまま表示しています。

Data Service Pattern

Each panel's data comes from a dedicated service module in src/services/. Services handle API calls, caching, error handling with circuit breaker pattern.

Circuit Breaker

The circuit breaker prevents cascading failures when an API is down. After N consecutive failures, it enters "cooldown" mode and serves cached data instead of hitting the API.

Create src/utils/circuit-breaker.ts:

interface CircuitState {
  failures: number;
  cooldownUntil: number;
}

interface CacheEntry<T> {
  data: T;
  timestamp: number;
}

export interface CircuitBreakerOptions {
  name: string;
  maxFailures?: number;
  cooldownMs?: number;
  cacheTtlMs?: number;
}

export class CircuitBreaker<T> {
  private state: CircuitState = { failures: 0, cooldownUntil: 0 };
  private cache: CacheEntry<T> | null = null;
  private name: string;
  private maxFailures: number;
  private cooldownMs: number;
  private cacheTtlMs: number;

  constructor(options: CircuitBreakerOptions) {
    this.name = options.name;
    this.maxFailures = options.maxFailures ?? 2;
    this.cooldownMs = options.cooldownMs ?? 5 * 60 * 1000;  // 5 minutes
    this.cacheTtlMs = options.cacheTtlMs ?? 10 * 60 * 1000; // 10 minutes
  }

  isOnCooldown(): boolean {
    if (Date.now() < this.state.cooldownUntil) return true;
    if (this.state.cooldownUntil > 0) {
      this.state = { failures: 0, cooldownUntil: 0 };
    }
    return false;
  }

  getCached(): T | null {
    if (this.cache && Date.now() - this.cache.timestamp < this.cacheTtlMs) {
      return this.cache.data;
    }
    return null;
  }

  recordSuccess(data: T): void {
    this.state = { failures: 0, cooldownUntil: 0 };
    this.cache = { data, timestamp: Date.now() };
  }

  recordFailure(error?: string): void {
    this.state.failures++;
    if (this.state.failures >= this.maxFailures) {
      this.state.cooldownUntil = Date.now() + this.cooldownMs;
      console.warn(`[${this.name}] Cooldown for ${this.cooldownMs / 1000}s`);
    }
  }

  async execute<R extends T>(fn: () => Promise<R>, defaultValue: R): Promise<R> {
    if (this.isOnCooldown()) {
      const cached = this.getCached();
      return (cached as R) ?? defaultValue;
    }
    const cached = this.getCached();
    if (cached !== null) return cached as R;
    try {
      const result = await fn();
      this.recordSuccess(result);
      return result;
    } catch (e) {
      console.error(`[${this.name}] Failed:`, e);
      this.recordFailure(String(e));
      return defaultValue;
    }
  }
}

export function createCircuitBreaker<T>(options: CircuitBreakerOptions): CircuitBreaker<T> {
  return new CircuitBreaker<T>(options);
}

Service Module Pattern

Each service is a TypeScript module that exports async data-fetching functions:

// src/services/stock-market.ts
import { createCircuitBreaker } from '../utils/circuit-breaker';

export interface StockQuote {
  symbol: string;
  name: string;
  price: number | null;
  change: number | null;
  sparkline?: number[];
}

const breaker = createCircuitBreaker<StockQuote[]>({
  name: 'StockMarket',
  cacheTtlMs: 60_000, // 1 minute cache
});

export async function fetchStockQuotes(symbols: string[]): Promise<StockQuote[]> {
  return breaker.execute(async () => {
    const params = new URLSearchParams({ symbols: symbols.join(',') });
    const resp = await fetch(`/api/stocks?${params}`);
    if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
    return resp.json();
  }, []);
}

Optional Query Parameter Pattern

When a service function accepts optional filter arguments (e.g. owner?, repo?, branch?), build the query string conditionally using URLSearchParams and only append a key when the value is defined. Never include undefined or empty-string values in the query string — omit the key entirely.

Template

export async function fetchItems(
  required: string,
  owner?: string,
  repo?: string,
  branch?: string,
): Promise<Item[]> {
  return breaker.execute(async () => {
    // 1. Start with required params
    const params = new URLSearchParams({ required });

    // 2. Conditionally append optional params
    if (owner)  params.set('owner',  owner);
    if (repo)   params.set('repo',   repo);
    if (branch) params.set('branch', branch);

    // 3. Append query string only when there are params
    const qs = params.toString();
    const url = qs ? `/api/items?${qs}` : '/api/items';

    const resp = aw
よくある質問

なぜURLSearchParamsを使うのですか?

値を安全にエンコードでき、設定されたフィルターだけを追加できるからです。

サービスは結果をキャッシュしますか?

はい。サービスにはキャッシュが含まれ、クールダウン中は保存されたデータを返します。

サーキットブレーカーのコードは含まれますか?

はい。スキルは、サービスと一緒に使うサーキットブレーカーのユーティリティを作る方法を示しています。

詳細

作者による元の説明

Create data fetching services with circuit breaker pattern for API resilience, including a first-class pattern for building optional query parameters via URLSearchParams. Services handle fetch, cache, retry, optional filters, and expose typed data to panel components.

repo: HKUDS/AgentPilot

人気

GitHubのスター
7.8k
ランキング
#13048
ライセンス
MIT
更新日
2026/11/1

このスキルは役に立ちますか?

0

ログイン して投票しましょう。

コメント

  • …

このリポジトリの他のスキル

似ているスキル