@darkchest/flux
v0.0.2
Published
@darkchest/flux是一个通过中间件链的形式将函数调用封装成流式(类似柯理化, 但是提供流的跳转与重试机制)执行链的工具包
Readme
@darkchest/flux
Dynamic Function Execution Flow with Middleware
flux 是一个轻量级、高可组合的库,用于管理 前置中间件 -> 函数执行 -> 后置中间件 这一完整流程。它通过可插拔的中间件机制,让你能够在前置、后置阶段注入逻辑,并提供了强大的流控制能力。
安装
npm install @darkchest/flux弹珠图
o1 - o2 - o3 - o4 - ... - o(n) - fn - oI - oII - oIII - oIV - ... - o(x) - ...
核心概念
- 安装 (flux.install): 创建一个围绕核心函数的工作流
- 中间件 (.use): 用于扩展功能的插件,分前置和后置
- 上下文 (ctx): 提供流控制方法的上下文对象
使用方法
基础用法
import flux from '@darkchest/flux';
// 定义核心函数
const fetchData = async (config) => {
const response = await fetch(config.url, { method: config.method });
return response.json();
};
// 创建工作流
const workflow = flux
.install(fetchData, { method: 'GET' })
.use(plugin1)
.use(plugin2)
.with(plugin3);
// 执行工作流
workflow({ url: '/api/users' }).then(finalResult => {
console.log('Final Result:', finalResult);
});中间件编写
// 前置中间件:参数校验
const plugin1 = async (config, ctx) => {
if (!config.url) {
throw new Error('URL is required');
}
config.headers = {
...config.headers,
'Authorization': `Bearer ${getToken()}`,
};
return config;
};
// 前置中间件:缓存处理
const plugin2 = async (config, ctx) => {
const cacheKey = JSON.stringify(config);
const cached = sessionStorage.getItem(cacheKey);
if (cached) {
return ctx.flush(JSON.parse(cached));
}
return config;
};
// 后置中间件:结果处理
const plugin3 = async (response, ctx) => {
if (response.code !== 0) {
throw new Error(`API Error: ${response.message}`);
}
return response.data;
};流控制
- ctx.next(config): 传递特定值给下一个前置中间件(一般不需要调用, 默认会读取当前中间件的入参传递给下一个中间件)
- ctx.exec(testConfig): 直接使用testConfig作为入参执行install注册的核心函数(用于测试函数内部逻辑)
- ctx.flush(mockResult): 跳转到后置中间件并mock核心函数结果(用于测试后置中间件或假数据预览)
- ctx.retry(1): 从安装的函数位置开始重试1次
API参考
flux.install(fn, defaultConfig = {}): workflow
创建新的工作流实例。
参数:
- fn: 要包装的核心函数
- defaultConfig: 默认配置 返回: 具有 .use 方法的 workflow 对象
workflow.use(middleware, config = {})
注册前置中间件。
参数:
- middleware: 前置中间件函数 返回: workflow 对象自身,支持链式调用
workflow.with(middleware, config = {})
注册后置中间件。
参数:
- middleware: 后置中间件函数 返回: workflow 对象自身,支持链式调用
许可证
MIT
