data-service
Screenshots
Installation
Review the source and dependencies with a prompt. A package is available to download.
Install with an AI assistant
Copy the prompt so your assistant can review the pinned revision and dependencies first.
View promptHide prompt
Check whether SkillPI Skill Finder is installed for your current agent. If it is missing, install and enable it using the official instructions at https://github.com/Findskills/skillpi. Then use Skill Finder to locate and install "data-service" from this exact SkillPI detail page: https://skillpi.com/skills/deepskill-247d6a401434f02c5e1f4ae481de6ffe06588cb385681a2b25c99a5448eedbbe. Verify the upstream source and version against https://github.com/HKUDS/OpenSpace before installing. If they do not match, stop and report the mismatch. Report the installed path and source version.
Source and setup
github.com
Setup guidance pending
See the original source for supported tools, dependencies, and permissions.
Installation test pending
Create a data-fetching service implementing the circuit breaker pattern to improve API resilience. The service is responsible for data retrieval, caching, and retries, and provides typed data to panel components.
Introduction source: third_party · HKUDS · 0.0.1 Reference
SkillPi interpretation
- Tasks
- Create data fetching services with circuit breaker pattern for API resilience. Services handle fetch, cache, retry, and expose typed data to panel components.
- Testing
- Not tested
Browse files
Frontmatter
name: data-service
description: Create data fetching services with circuit breaker pattern for API resilience. Services handle fetch, cache, retry, and expose typed data to panel components.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.
Current listing version
0.0.1
Safety and assessment details
Quality assessment
Out of 100 · Assessment report from SkillPi LAB.
Areas to improve
-
缺少 When to Use 章节 Reported severity: Minor
文档未明确说明何时使用此模式,缺乏使用场景指导
Recommendation: 建议添加 When to Use 章节,说明适合使用此数据服务模式的场景和条件
Highlights
- 提供完整的熔断器模式实现,有效防止 API 级联故障
- 包含缓存和重试机制,提升数据获取的弹性和可靠性
- 提供类型化的数据接口,便于面板组件使用
Areas to improve
-
触发词可进一步细化 Reported severity: Minor
description 可更具体地描述适用场景和技术栈
Recommendation: 建议在 description 中补充适用场景如'适用于需要高可用数据获取的前端应用',以及技术栈信息
Highlights
- 触发词清晰准确地描述了核心功能:熔断器模式的数据获取服务
- 涵盖了数据获取、缓存、重试等关键特性,边界定义明确
Areas to improve
-
文档结构可进一步优化 Reported severity: Minor
虽然结构完整,但可考虑添加目录或导航提升可读性
Recommendation: 建议添加文档目录或章节导航,方便用户快速定位所需内容
Highlights
- 文档结构清晰,包含实现代码、使用模式和最佳实践
- 提供了完整的 TypeScript 实现和多个代码示例
- frontmatter 完整,符合规范要求
Areas to improve
-
缺少测试说明 Reported severity: Minor
未提供测试策略或测试示例,影响执行可靠性验证
Recommendation: 建议添加测试说明或测试示例,确保代码的可靠性和可维护性
Highlights
- 提供了完整的错误处理机制和默认值回退策略
- 包含缓存 TTL 和熔断器参数配置,适应不同场景需求
- 代码实现完整,可直接用于生产环境
The arithmetic mean of the first four original scores, rounded to a whole number.
Static text checks
100 / 100 · skillpi-20261123-no-r3-v1
No current rules matched the text.
This score reflects rule matches in the text and is provided for reference before use. It excludes attachments and runtime behavior.
Permissions and checks before use
Automatically summarized from this main document. Matches may be examples or defensive advice; they are not actual permission declarations. Attachments, external dependencies and runtime behavior are not covered.
-
Accounts, secrets or authorization
Use a dedicated least-privilege account. Keep secrets out of public content and command logs; verify the receiving service and tenant.
Mentioned in main document · lines 149, 150
Domains or addresses referenced in the document
These addresses may be documentation links or examples, not an approved network allowlist. Verify actual destinations and outgoing data before use.
- finnhub.io
Security rating and access scope
safe · Static evidence review; not a runtime safety guarantee.
Before use, confirm and authorize actual file access, external services and network destinations in your host. This review grants no runtime permissions.
User discussion
No verified reviews yet.