data-service
O que ela faz
Esta skill mostra ao agente de IA como escrever um módulo de serviço de dados para cada painel do dashboard. É para desenvolvedores que querem as chamadas de API tratadas em um único lugar confiável por painel.
Quando usar
- ✓Quando cada painel do dashboard precisa do próprio serviço de dados para buscar e guardar informações em cache.
- ✓Quando uma API externa pode falhar e você quer um circuit breaker para limitar o estrago.
- ✓Quando os painéis precisam receber dados tipados de um serviço.
Link da skill
https://github.com/HKUDS/AgentPilot/blob/main/openspace/legacy/v1/showcase/skills/data-service/SKILL.mdCopie e cole na sua IA (Claude, ChatGPT ou Cursor) pedindo para seguir as instruções.
Como usar
O jeito mais fácil: copie a mensagem e cole na sua IA. Ela lê a skill e segue as instruções.
Mensagem pronta para colar
Para Claude Code, Codex ou Cursor: rode na pasta do projeto e a skill fica instalada.
Baixe o SKILL.md e coloque na pasta de skills do seu agente.
Exemplo do que pedir para a IA
“Configure o serviço de dados do meu painel de preços de criptomoedas, com cache e circuit breaker para que continue no ar quando a API estiver lenta.”
5 skills novas por semana. 1 minuto de leitura.
Como funciona
O agente cria um utilitário de circuit breaker que controla falhas e pausas e depois escreve um serviço na pasta de serviços. O serviço busca os dados, guarda-os em um cache de curta duração e devolve resultados tipados ao painel.
Conteúdo técnico (SKILL.md original)
Texto original do autor, em inglês, direto do 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
- One circuit breaker per API endpoint — create at module level
- Export typed interfaces for data shapes
- Wrap fetch calls in
breaker.execute(fn, defaultValue) - Default values are empty arrays
[]or empty objects{} - Services are stateless modules — no class instances, just exported functions
- 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.
Perguntas frequentes
Onde ficam os serviços?
A skill coloca o serviço de cada painel em um módulo próprio dentro da pasta de serviços.
O que faz o cache?
Ele guarda resultados recentes para que o painel mostre dados enquanto a API está fora do ar ou em pausa.
Qual é a pausa do breaker?
Os padrões da skill incluem um período de pausa depois de falhas repetidas, que pode ser alterado.
Detalhes
Descrição original do autor
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
Popularidade
- Estrelas no GitHub
- 7,8 mil
- Posição no ranking
- #13050
- Licença
- MIT
- Atualizada em
- 01/11/2026
Comentários
- …
Mais skills deste repositório
agentpilot
7,8 milAjuda seu agente a melhorar um projeto passo a passo, preparando uma tarefa e executando o ciclo do AgentPilot, que propõe, testa e pontua mudanças.
openspace
7,8 milAjuda seu agente a configurar o OpenSpace, uma ferramenta que armazena e busca skills de agentes, e a conectá-la ao seu app de IA pelo MCP.
rsi-arena
7,8 milAjuda seu agente a configurar e rodar testes padrão de benchmark de IA, como AIME e Terminal-Bench, para comparar diferentes métodos de melhoria.
experiment-guide
7,8 milAjuda seu agente a planejar pequenos experimentos, ler seus resultados e registrar descobertas enquanto investiga como melhorar um programa.
Skills parecidas
angular-developer
280 milAjuda seu agente a criar código Angular e a dar conselhos sobre a estrutura do projeto. É útil para iniciar novos projetos, criar partes do código ou melhorar a performance e acessibilidade.
frontend-a11y
280 milAjuda seu agente a tornar interfaces web acessíveis para todos. Ele garante que sites e apps funcionem bem com leitores de tela e navegação por teclado.
frontend-patterns
280 milFaz seu agente aplicar padrões modernos no desenvolvimento frontend. Ele otimiza performance, gerencia estado e segue boas práticas em React e Next.js.