data-service

创建具备熔断器模式的数据获取服务,以提升 API 的弹性。该服务负责数据获取、缓存与重试,并向面板组件提供类型化的数据。

仓库最近推送
GitHub Stars
8,134
Forks
953
Issues / PRs
39

预览截图

来自skillπ 实验室的展示

安装方式

先用 Prompt 核对来源与依赖。也可下载安装包。

用 AI 助手安装

复制提示词,让助手先核对固定版本和依赖。

查看 Prompt收起 Prompt
先检查当前 Agent 是否已安装 SkillPI Skill Finder。如果尚未安装,请按官方仓库的说明安装并启用:https://github.com/Findskills/skillpi。然后使用 Skill Finder 打开此 SkillPI 详情页并定位 "data-service":https://skillpi.com/zh/skills/deepskill-247d6a401434f02c5e1f4ae481de6ffe06588cb385681a2b25c99a5448eedbbe。安装前核对上游来源和版本:https://github.com/HKUDS/OpenSpace。来源不一致时停止并说明差异。核对通过后,用 Skill Finder 安装目标 Skill,并报告安装路径和来源版本。

来源与配置

github.com

配置方式待核实

请查看原始来源中的适用工具、依赖和权限要求。

安装实测待补充

创建具备熔断器模式的数据获取服务,以提升 API 的弹性。该服务负责数据获取、缓存与重试,并向面板组件提供类型化的数据。

0 下载

介绍来源: third_party · HKUDS · 0.0.1 参考来源

SkillPi 解读

能完成的任务
创建带有断路器模式的数据获取服务,用于API的复原力. 服务处理抓取,缓存,重试,并将输入的数据暴露在面板组件中.
实测状态
未测试

文件浏览

在原站浏览文件 ↗

原始 SKILL.md

打开原文 ↗
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

  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.

当前收录版本

0.0.1

核对来源版本 ↗

安全与评测信息

质量评测

满分100 · 来自 SkillPi LAB 实验室的评测报告。

场景价值78/100

待提升项

  • 缺少 When to Use 章节 原报告严重程度:轻微

    文档未明确说明何时使用此模式,缺乏使用场景指导

    改进建议:建议添加 When to Use 章节,说明适合使用此数据服务模式的场景和条件

亮点

  • 提供完整的熔断器模式实现,有效防止 API 级联故障
  • 包含缓存和重试机制,提升数据获取的弹性和可靠性
  • 提供类型化的数据接口,便于面板组件使用
触发精准88/100

待提升项

  • 触发词可进一步细化 原报告严重程度:轻微

    description 可更具体地描述适用场景和技术栈

    改进建议:建议在 description 中补充适用场景如'适用于需要高可用数据获取的前端应用',以及技术栈信息

亮点

  • 触发词清晰准确地描述了核心功能:熔断器模式的数据获取服务
  • 涵盖了数据获取、缓存、重试等关键特性,边界定义明确
结构规范92/100

待提升项

  • 文档结构可进一步优化 原报告严重程度:轻微

    虽然结构完整,但可考虑添加目录或导航提升可读性

    改进建议:建议添加文档目录或章节导航,方便用户快速定位所需内容

亮点

  • 文档结构清晰,包含实现代码、使用模式和最佳实践
  • 提供了完整的 TypeScript 实现和多个代码示例
  • frontmatter 完整,符合规范要求
执行可靠85/100

待提升项

  • 缺少测试说明 原报告严重程度:轻微

    未提供测试策略或测试示例,影响执行可靠性验证

    改进建议:建议添加测试说明或测试示例,确保代码的可靠性和可维护性

亮点

  • 提供了完整的错误处理机制和默认值回退策略
  • 包含缓存 TTL 和熔断器参数配置,适应不同场景需求
  • 代码实现完整,可直接用于生产环境
证据可验 (前四项均值)86/100

取前四项原始分值的算术平均,四舍五入取整。可通过收录报告核对各项评分与说明,运行记录需单独查证。

正文静态检测

100 / 100 · skillpi-20261123-no-r3-v1

正文未命中当前规则。

分数仅反映正文中的规则命中,供使用前参考。附件与运行行为不在此评分范围内。

权限与使用前检查

根据当前主文档自动整理,命中内容可能是示例或防护说明;不是实际权限声明,也未覆盖附件、外部依赖或运行行为。

  • 账号、密钥或授权

    使用专用、最小权限账号,不把密钥粘贴到公开内容或命令日志;核对接收数据的服务与租户。

    主文档提及 · 第 149, 150 行
文档引用的域名或地址

这些地址可能用于文档链接或示例,不是已批准的联网清单。使用前核对实际目的地及发送的数据。

  • finnhub.io

本站展示提示不会授予权限。涉及文件改动、密钥、外部发送或费用时,仍由你使用的工具按需确认。

安全评级与访问范围

safe · 静态证据核验,不代表运行安全保证。

使用前请由宿主核对并授权实际文件读写、外部服务和联网目的地;本站的核验不会授予任何运行权限。