|
| 1 | +/** |
| 2 | + * Example 1: High-spending customer discount |
| 3 | + * Run from project root: node examples/01-high-spending-discount.mjs |
| 4 | + * (Run "npm run build" first.) |
| 5 | + */ |
| 6 | +import { Fact, Condition, Conditions, Rule, RuleEngine } from '../dist/index.js'; |
| 7 | + |
| 8 | +const transactionFact = new Fact('transaction'); |
| 9 | +transactionFact.setFact = { amount: 600 }; |
| 10 | +const customerStatusFact = new Fact('customer_status'); |
| 11 | +customerStatusFact.setFact = { status: 'gold' }; |
| 12 | + |
| 13 | +const condition1 = new Condition(); |
| 14 | +condition1.fact('transaction').operator('greaterThan').value(500).path('amount'); |
| 15 | +const condition2 = new Condition(); |
| 16 | +condition2.fact('customer_status').operator('equal').value('gold').path('status'); |
| 17 | + |
| 18 | +const conditions = new Conditions('promoEligibility'); |
| 19 | +conditions.all([condition1.getCondition, condition2.getCondition]); |
| 20 | + |
| 21 | +const rule = new Rule('applyDiscount'); |
| 22 | +rule.conditions('promoEligibility') |
| 23 | + .event('discount', { discount: 10 }) |
| 24 | + .priority(1) |
| 25 | + .onSuccess(() => console.log('Discount applied successfully')) |
| 26 | + .onFailure(() => console.log('Discount could not be applied')); |
| 27 | + |
| 28 | +const ruleEngine = new RuleEngine(); |
| 29 | +const results = await ruleEngine.run(); |
| 30 | +console.log('Events:', results.events.length); |
| 31 | +console.log('First event type:', results.events[0]?.type); |
| 32 | +console.log('OK: High-spending discount example passed.\n'); |
0 commit comments