Skip to content

Commit 4e6aa1f

Browse files
chris-pardychris-pardy-newfire
authored andcommitted
Making the on method of engine generic
When subscribing to events directly from rules instead of the success and failure events the on method has the wrong signature for the event handler make it generic to fix it. Replaces CacheControl#370 Co-Author Michael J. Shalewski <mshalewski@outlook.com>
1 parent f4ed36e commit 4e6aa1f

File tree

2 files changed

+18
-5
lines changed

2 files changed

+18
-5
lines changed

types/index.d.ts

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -51,9 +51,7 @@ export class Engine {
5151
removeFact(factOrId: string | Fact): boolean;
5252
getFact<T>(factId: string): Fact<T>;
5353

54-
on(eventName: "success", handler: EventHandler): this;
55-
on(eventName: "failure", handler: EventHandler): this;
56-
on(eventName: string, handler: EventHandler): this;
54+
on<TEvent = Event>(eventName: string, handler: EventHandler<TEvent>): this;
5755

5856
run(facts?: Record<string, any>, runOptions?: RunOptions): Promise<EngineResult>;
5957
stop(): this;
@@ -119,8 +117,8 @@ export interface Event {
119117

120118
export type PathResolver = (value: object, path: string) => any;
121119

122-
export type EventHandler = (
123-
event: Event,
120+
export type EventHandler<TEvent = Event> = (
121+
event: TEvent,
124122
almanac: Almanac,
125123
ruleResult: RuleResult
126124
) => void;

types/index.test-d.ts

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,13 @@ import rulesEngine, {
44
Almanac,
55
EngineResult,
66
Engine,
7+
Event,
78
Fact,
89
Operator,
910
OperatorEvaluator,
1011
PathResolver,
1112
Rule,
13+
RuleResult,
1214
RuleProperties,
1315
RuleSerializable
1416
} from "../";
@@ -94,6 +96,19 @@ expectType<Engine>(engine.addFact(dynamicFact));
9496
expectType<boolean>(engine.removeFact(fact));
9597
expectType<Fact<string>>(engine.getFact<string>("test"));
9698

99+
// event handlers
100+
engine.on("failure", (event, almanac, ruleResult) => {
101+
expectType<Event>(event)
102+
expectType<Almanac>(almanac)
103+
expectType<RuleResult>(ruleResult)
104+
});
105+
106+
engine.on<{ test: true }>("test", (event, almanac, ruleResult) => {
107+
expectType<{ test: true }>(event);
108+
expectType<Almanac>(almanac);
109+
expectType<RuleResult>(ruleResult);
110+
});
111+
97112
// Run the Engine
98113
expectType<Promise<EngineResult>>(engine.run({ displayMessage: true }));
99114

0 commit comments

Comments
 (0)