跳到主要内容

Decorator Function

装饰函数在不修改原函数签名的前提下,为其增加日志、重试、计时等横切行为,形态上接近「函数装饰器」。

项目中的实现

  • 源码: src/decoratorFunction.ts
  • 导出: withLoggingwithRetry

各函数示例

withLogging

import { withLogging } from 'wssf-kage-js';

const fetchUser = withLogging('fetchUser', (id: number) => ({ id, name: 'Ada' }));
fetchUser(1);

withRetry

import { withRetry } from 'wssf-kage-js';

const unstable = withRetry(2, async () => {
const res = await fetch('/api');
if (!res.ok) throw new Error('fail');
return res.json();
});

什么时候优先用

  • 需要快速为已有函数加上可观测性(日志、调试)
  • 异步调用需要有限次重试且希望与业务函数解耦