@clippboard-health/rules-engine (英语)
一个纯粹的功能规则引擎,以保持逻辑通情达理的代码简单,可靠,可理解和可解释.
引擎使用代码中创建的静态规则,而不是将动态规则序列化到数据库,因为我们还没有需要后者.
目录
安装
npm install @clipboard-health/rules-engine
使用量
import { deepEqual } from "node:assert/strict";
import {
all,
allIf,
appendOutput,
firstMatch,
type Rule,
type RuleContext,
} from "@clipboard-health/rules-engine";
interface Input {
a: number;
b: number;
}
interface Output {
result: number;
}
const exampleContext: RuleContext<Input, Output> = {
input: {
a: 2,
b: 5,
},
output: [],
};
const addNumbersIfPositiveRule: Rule<Input, Output> = {
runIf: (input) => input.a > 0 && input.b > 0,
run: (context) => {
const { a, b } = context.input;
return appendOutput(context, { result: a + b });
},
};
const multiplyNumbersIfPositiveRule: Rule<Input, Output> = {
runIf: (input) => input.a > 0 && input.b > 0,
run: (context) => {
const { a, b } = context.input;
return appendOutput(context, { result: a * b });
},
};
const divideNumbersIfNegative: Rule<Input, Output> = {
runIf: (input) => input.a < 0 && input.b < 0,
run: (context) => {
const { a, b } = context.input;
return appendOutput(context, { result: a / b });
},
};
// Using all() applies all the rules to the context
const allResult = all(
addNumbersIfPositiveRule,
divideNumbersIfNegative,
multiplyNumbersIfPositiveRule,
).run(exampleContext);
deepEqual(allResult.output, [{ result: 7 }, { result: 10 }]);
// Using firstMatch() applies the first the rules to the context
const firstMatchResult = firstMatch(
divideNumbersIfNegative,
addNumbersIfPositiveRule,
multiplyNumbersIfPositiveRule,
).run(exampleContext);
deepEqual(firstMatchResult.output, [{ result: 7 }]);
// Using allIf() applies all the rules that return true for `runIf` to the context when the predicate
// (a function received as firs argument) returns true
const allIfResult = allIf(
(input) => input.a === 2,
divideNumbersIfNegative,
addNumbersIfPositiveRule,
multiplyNumbersIfPositiveRule,
).run(exampleContext);
deepEqual(allIfResult.output, [{ result: 7 }, { result: 10 }]);
地方发展指挥部
见 package.json scripts 用于命令列表.