跳到主要内容

Higher Order Function

高阶函数用于包装和增强业务函数,非常适合处理权限、审计、性能、降级这类横切关注点。以下为 src/higherOrder.ts 中每个 with* 导出各一例(类型导出略)。

项目中的实现

  • 源码: src/higherOrder.ts

各函数示例

withPermission

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

const getUser = () => ({ roles: ['admin'] });
const safe = withPermission('admin', getUser)((id: number) => id);
safe(1);

withPerformance

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

const timed = withPerformance('fetch')(async () => 'ok');
await timed();

withTokenAudit

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

const audited = withTokenAudit(
'gpt-test',
(res: string) => res.length,
(record) => console.log(record)
)(async () => 'response text');
await audited();

withFallback

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

const safe = withFallback([])(async () => {
throw new Error('fail');
});
await safe(); // => []

withSanitizer

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

const clean = withSanitizer({ clean: (v) => (typeof v === 'string' ? v.trim() : v) })(
(a: string, b: number) => `${a}:${b}`
);
clean(' x ', 1);

withLock

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

const locked = withLock(async () => 'done');
await locked();
await locked(); // 并发第二次可能得到 undefined(锁定中)

withAuditTrail

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

const buffer: { actionType: string; params: unknown[]; timestamp: number }[] = [];
const fn = withAuditTrail('DELETE', (r) => buffer.push(r))((id: number) => id);
fn(42);

withUIFormat

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

const api = withUIFormat((raw: { n: number }) => ({ label: String(raw.n) }))(async () => ({
n: 7
}));
await api();

最典型的价值

  • 把横切逻辑从业务函数里剥离出去
  • 让业务函数保持纯净
  • 让 AI 更容易批量生成统一模式代码