npm i rete rete-engine
Розглянемо простий приклад графа з двома типами вузлів: Log
і Delay
. Ці вузли можуть виконувати певні операції та певним чином передавати керування вихідним вузлам.
У кінці статті ви можете знайти посилання на повний приклад, який включає візуальні компоненти.
Визначення класу вузла, який реєструє повідомлення та передає керування вихідним вузлам через порт exec
:
const socket = new ClassicPreset.Socket("socket");
class Log extends ClassicPreset.Node {
constructor(public message: string) {
super("Log");
this.addInput("exec", new ClassicPreset.Input(socket, "Exec", true));
this.addOutput("exec", new ClassicPreset.Output(socket, "Exec"));
}
execute(input: "exec", forward: (output: "exec") => void) {
console.log(this.message);
forward("exec");
}
}
Визначення класу, який обробляє затримку, де єдиною метою є передача керування вихідним вузлам через порт exec
після визначеного часу очікування:
class Delay extends ClassicPreset.Node {
constructor(private seconds: number) {
super("Delay");
this.addInput("exec", new ClassicPreset.Input(socket, "Exec", true));
this.addOutput("exec", new ClassicPreset.Output(socket, "Exec"));
}
execute(input: "exec" | undefined, forward: (output: "exec") => void) {
setTimeout(() => forward("exec"), seconds * 1000)
}
}
class Connection<A extends NodeProps, B extends NodeProps> extends ClassicPreset.Connection<A, B> {}
type NodeProps = Start | Log | Delay;
type ConnProps =
| Connection<Start, Log>
| Connection<Delay, Log>
| Connection<Log, Delay>
| Connection<Log, Log>
| Connection<Delay, Delay>;
type Schemes = GetSchemes<NodeProps, ConnProps>;
import { ControlFlowEngine } from "rete-engine";
import { NodeEditor } from "rete";
const editor = new NodeEditor<Schemes>();
const engine = new ControlFlowEngine<Schemes>();
editor.use(engine);
Давайте додамо послідовність вузлів у формі Log -> Delay -> Log
const log1 = new Log("log before delay");
const delay = new Delay(2);
const log2 = new Log("log after delay");
const con2 = new Connection(log1, "exec", delay, "exec");
const con3 = new Connection(delay, "exec", log2, "exec");
await editor.addNode(log1);
await editor.addNode(delay);
await editor.addNode(log2);
await editor.addConnection(con2);
await editor.addConnection(con3);
Вузол log1
служить початковою точкою для виконання графа.
engine.execute(log1.id);
Ця операція запускає метод execute
класу Log
з undefined
як параметр input
, оскільки вузол був викликаний безпосередньо, без передачі від вхідного вузла.
Потім виклик forward("exec")
передає керування всім вихідним вузлам. У нашому випадку вузол Delay
робить те саме, але після затримки з використанням setTimeout
.
Логи:
"log before delay"
// delay for 2 seconds
"log after delay"
Перегляньте повний результат на сторінці прикладу Control flow.