본문으로 건너뛰기
Skillpedia
웹사이트 및 UI (프런트엔드)7.8k · #13050

data-service

하는 일

이 스킬은 대시보드 패널마다 데이터 서비스 모듈을 작성하는 방법을 AI 에이전트에게 보여 줍니다. 패널별로 API 호출을 한 곳에서 안정적으로 처리하려는 개발자를 위한 스킬입니다.

사용하는 경우

  • ✓각 대시보드 패널이 정보를 가져오고 캐시하는 자체 데이터 서비스가 필요할 때.
  • ✓외부 API가 실패할 수 있고 서킷 브레이커로 피해를 줄이고 싶을 때.
  • ✓패널에 타입이 지정된 데이터를 서비스에서 넘겨주어야 할 때.

스킬 링크

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

복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.

사용 방법

가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.

바로 붙여넣을 수 있는 메시지

Use this skill to help me: https://github.com/HKUDS/AgentPilot/blob/main/openspace/legacy/v1/showcase/skills/data-service/SKILL.md Read the SKILL.md file at that link and follow its instructions for my task.
AI가 이런 스킬을 알아서 찾아 쓰길 원하시나요?무료 Skillpedia MCP를 설치하세요. 한 줄이면 작업마다 스킬 15,000+개 중에서 검색합니다.1분 만에 설치 →

AI에게 요청하는 예시

“제 암호화폐 시세 패널의 데이터 서비스를 설정해 주세요. API가 느려도 작동을 유지하도록 캐싱과 서킷 브레이커를 넣어 주세요.”

매주 새 스킬 5개. 읽는 데 1분.

작동 방식

에이전트는 실패와 쿨다운을 추적하는 서킷 브레이커 유틸리티를 만든 다음, services 폴더에 서비스를 작성합니다. 서비스는 데이터를 가져오고, 짧게 유지되는 캐시에 저장하며, 타입이 지정된 결과를 패널에 돌려줍니다.

기술 내용 (원본 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();
  }, []);
}

Key Patterns

  1. One circuit breaker per API endpoint — create at module level
  2. Export typed interfaces for data shapes
  3. Wrap fetch calls in breaker.execute(fn, defaultValue)
  4. Default values are empty arrays [] or empty objects {}
  5. Services are stateless modules — no class instances, just exported functions
  6. API proxy: Frontend calls /api/... which proxies to external APIs (hides API keys)

API Proxy Pattern

For APIs requiring keys, create server-side proxy endpoints:

// api/stocks.ts (Vercel serverless function)
export default async function handler(req, res) {
  const { symbols } = req.query;
  const apiKey = process.env.FINNHUB_API_KEY;
  const data = await fetch(`https://finnhub.io/api/v1/quote?symbol=${symbols}&token=${apiKey}`);
  res.json(await data.json());
}

This keeps API keys server-side and provides a single endpoint for the frontend.

자주 묻는 질문

서비스는 어디에 두나요?

스킬은 각 패널의 서비스를 services 폴더 안의 전용 모듈에 두라고 안내합니다.

캐시는 무엇을 하나요?

최근 결과를 저장해 API가 내려갔거나 쿨다운 중일 때도 패널이 데이터를 보여 줄 수 있게 합니다.

브레이커의 쿨다운은 무엇인가요?

스킬의 기본값에는 반복된 실패 후의 쿨다운 기간이 있으며, 바꿀 수 있습니다.

상세 정보

작성자의 원본 설명

Create data fetching services with circuit breaker pattern for API resilience. Services handle fetch, cache, retry, and expose typed data to panel components.

repo: HKUDS/AgentPilot

인기도

GitHub 스타
7.8k
순위
#13050
라이선스
MIT
업데이트
2026. 11. 1.

이 스킬이 유용한가요?

0

로그인 투표하려면 로그인하세요.

댓글

  • …

이 저장소의 다른 스킬

비슷한 스킬