@edgeone/ef-flow
v1.0.1
Published
Flow - Focused on developing multifunctional edge gateway services
Downloads
45
Maintainers
Readme
@edgeone/ef-flow
@edgeone/ef-flow
是适用于 EdgeOne 边缘函数的边缘网关 SDK,支持请求分发、多维条件判断、请求响应改写等功能。
概述
需求:
- 请求分发器(一个入口,多个出口:根据不同条件,去往不同出口);
- 分发条件可以自由组合;
- 支持在不同阶段自定义回调函数,同时,回调函数支持中间件管道的形式;
定义:
- 资源(resource):在整个分发流程中,资源只是代指 url,只有 fetch(url) 后才会拿到实际的资源 response;
- 规则(rule):规则由条件组成,我们使用规则来控制请求,即规则定义了在哪些场景下,请求会分发到某一资源出口;
- 条件(condition):规则由一个个条件构成,满足了所有条件,即命中这个规则;
设计原则:
- 以资源为基准,而不是以条件为基准:即“一条规则面向一个资源”;
- 一条规则可包含多个条件,多个条件之间是“与”关系:即“满足所有条件才算是命中这条规则”;
- 多条规则之间是“或”关系:即“命中了一条规则,就不会命中其他规则,这样最终只有一个资源出口”;
安装
npm i @edgeone/ef-flow
使用
import { Distributor, DistributeCallback, DistributeHook, DistributeRule } from '../src/index';
const hook1: DistributeHook = (request) => {
console.log('hook1');
return request;
};
const hook2: DistributeHook = (request) => {
console.log('hook2');
return request;
};
const callback1: DistributeCallback = (_request, response, _rule) => {
console.log('callback1');
return response;
};
const callback2: DistributeCallback = (_request, response, _rule) => {
console.log('callback2');
return response;
};
const commonHook1: DistributeHook = (request) => {
console.log('commonHook1');
return request;
};
const commonCallback1: DistributeCallback = (_request, response) => {
console.log('commonCallback1');
return response;
};
const rules: DistributeRule[] = [
{
conditions: [
{
type: 'header',
target: 'User-Agent',
operator: 'includes',
values: ['Mozilla'],
},
],
resource: 'https://tencent.com/',
hook: [hook1, hook2],
callback: [callback1, callback2],
},
];
async function handleDistribution(event: FetchEvent) {
const distributor = new Distributor({
event,
rules,
hook: [commonHook1],
callback: [commonCallback1],
});
await distributor.handle();
}
addEventListener('fetch', (event) => {
event.passThroughOnException();
handleDistribution(event);
});