跳到正文
Skillpedia
网站与界面(前端)7.8k · #13048

data-service-optional-params

它能做什么

这项技能指导智能体编写接受可选筛选条件的仪表板数据服务。适合 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。它会读取这个技能并按说明操作。

可直接粘贴的消息

请用这个技能帮我:https://github.com/HKUDS/AgentPilot/blob/main/openspace/legacy/v1/showcase/skills/data-service-optional-params/SKILL.md 阅读该链接中的 SKILL.md 文件,并在我的任务中按照它的说明来做。
想让你的 AI 自己找到这样的技能吗?安装免费的 Skillpedia MCP:只需一行,每次任务前它都会在 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

登录 后即可投票。

评论

  • …

同一仓库的更多技能

相似技能