Skip to content

Docs: Rules

ng-druid edited this page Aug 8, 2025 · 1 revision

Documentation for Angular Rules Library


Table of Contents

  1. Introduction
  2. Installation
  3. Overview
  4. Key Concepts
    • Rule Parsing
    • Rule Resolution
    • Rule Evaluation
  5. Core Components
    • RulesModule
  6. Key Services
    • RulesParserService
    • RulesResolverService
  7. Usage
    • Parsing Rules
    • Resolving Rules
    • Evaluating Rules
  8. API Reference
  9. Examples
  10. Testing

1. Introduction

The Angular Rules Library provides tools for defining, parsing, resolving, and evaluating rules in applications. It helps integrate rule-based logic into Angular projects using advanced parsing mechanisms, rule evaluation engines, and nested conditions. It is lightweight and extensible, making it easy to dynamically handle rules.


2. Installation

Install the library along with its dependencies:

npm install @rollthecloudinc/ngx-angular-query-builder @rollthecloudinc/attributes @rollthecloudinc/context json-rules-engine uuid

3. Overview

The Rules Library is designed to help developers implement rule-based workflows. It provides services for the creation, parsing, and evaluation of rules in complex applications using tools like JSON rules engines and field mappings.

Features:

  • Rule Parsing: Convert data structures into rules or fields.
  • Rule Resolution: Resolve rules with external context or nested conditions.
  • Rule Evaluation: Evaluate rule sets dynamically with facts and conditions.

4. Key Concepts

4.1 Rule Parsing

The library allows parsing objects, attributes, or fields into manageable rules and conditions. Using the RulesParserService, developers can generate rule structures compatible with JSON rule engines.

4.2 Rule Resolution

Rules can be resolved with the help of inline contexts or external configuration using the RulesResolverService. It supports merging contexts and evaluating nested rule structures for complex workflows.

4.3 Rule Evaluation

Rules are evaluated using factual inputs and the json-rules-engine. Rule evaluation supports nested conditions (and, or) and events, enabling dynamic workflows based on rule logic.


5. Core Components

RulesModule

The RulesModule encapsulates all services provided by the library. Importing this module makes the services available throughout your Angular application.


6. Key Services

RulesParserService

The RulesParserService provides methods for parsing data into fields, attribute mappings, and engine-compatible rule structures. It contains logic for handling complex attribute values and nested rule conditions.

Key Responsibilities:

  • Parse objects and attributes into reusable Field structures.
  • Convert rule sets into JSON engine-compatible rules.
  • Resolve field types dynamically (e.g., number, string, boolean).

Example:

import { RulesParserService } from './services/rules-parser.service';

constructor(private rulesParser: RulesParserService) {}

ngOnInit() {
  const fields = this.rulesParser.buildFields({ age: 30, name: "John" });
  console.log('Parsed Fields:', fields);
}

RulesResolverService

The RulesResolverService resolves rule sets dynamically with context and evaluates them using the json-rules-engine. It manages inline contexts and combines facts for complex workflows.

Key Responsibilities:

  • Resolve rules with dynamic inline contexts.
  • Evaluate rules using provided facts and return results.
  • Handle nested rule conditions (and/or) efficiently.

Example:

import { RulesResolverService } from './services/rules-resolver.service';

constructor(private rulesResolver: RulesResolverService) {}

ngOnInit() {
  const ruleSet = { condition: "or", rules: [{ field: "age", operator: ">", value: 18 }] };
  this.rulesResolver.evaluate(ruleSet).subscribe(result => {
    console.log('Rule is visible:', result);
  });
}

7. Usage

7.1 Parsing Rules

Use the RulesParserService to convert data objects or attribute arrays into reusable fields or engine-compatible rules.

Example:

const parsedFields = rulesParser.buildFields({ age: 30, isActive: true });
console.log('Parsed Fields:', parsedFields);

7.2 Resolving Rules

Leverage the RulesResolverService to resolve rules dynamically with inline contexts. This allows integration with external rules or nested sets.

Example:

const context = [{ name: "userContext", attributes: [{ name: "age", value: 25 }] }];
rulesResolver.evaluate(ruleSet, context).subscribe(result => {
  console.log('Evaluation Result:', result);
});

7.3 Evaluating Rules

Evaluate rule sets with facts using the JSON rules engine, resolving conditions like and/or dynamically.

Example:

const ruleSet = { condition: "and", rules: [{ field: "user.age", operator: ">", value: 18 }] };
rulesResolver.evaluate(ruleSet).subscribe(isVisible => {
  console.log('Rule Evaluation:', isVisible);
});

8. API Reference

Classes

  1. RulesParserService

    • buildFields(obj: any, prefix?: string): Map<string, Field>: Parses an object into fields.
    • toEngineRule(ruleSet: RuleSet): Rule: Converts a rule set into an engine-compatible rule structure.
    • resolveNativeType(type: string): string: Resolves JavaScript native types to field types.
    • resolveAttributeType(type: AttributeTypes): string: Resolves attribute types to field types.
  2. RulesResolverService

    • evaluate(ruleSet: RuleSet, contexts?: Array<InlineContext>): Observable<boolean>: Evaluates a rule set with the given contexts.
    • Dependencies: InlineContextResolverService, json-rules-engine.

9. Examples

Example 1: Parsing Data into Fields

import { RulesParserService } from './services/rules-parser.service';

const data = { age: 30, isActive: true };
const fields = rulesParser.buildFields(data);
console.log('Fields:', fields);

Example 2: Evaluating Rules with Contexts

import { RulesResolverService } from './services/rules-resolver.service';

const ruleSet = {
  condition: "and",
  rules: [
    { field: "user.age", operator: ">", value: 18 },
    { field: "user.isActive", operator: "=", value: true }
  ]
};

const userContext = [{ name: "userContext", attributes: [{ name: "age", value: 25 }, { name: "isActive", value: true }] }];

rulesResolver.evaluate(ruleSet, userContext).subscribe(result => {
  console.log('Rule Evaluated Result:', result); // Output: true
});

10. Testing

Example: Test for RulesParserService

import { RulesParserService } from './services/rules-parser.service';

describe('RulesParserService', () => {
  let parserService: RulesParserService;

  beforeEach(() => {
    parserService = new RulesParserService();
  });

  it('should parse object into fields', () => {
    const fields = parserService.buildFields({ age: 30 });
    expect(fields.has('age')).toBeTruthy();
    expect(fields.get('age')).toEqual({ name: 'age', type: 'number', defaultValue: 30 });
  });

  it('should resolve native types correctly', () => {
    expect(parserService.resolveNativeType('string')).toBe('string');
    expect(parserService.resolveNativeType('number')).toBe('number');
    expect(parserService.resolveNativeType('boolean')).toBe('boolean');
  });
});

Example: Test for RulesResolverService

import { RulesResolverService } from './services/rules-resolver.service';

describe('RulesResolverService', () => {
  let resolverService: RulesResolverService;

  beforeEach(() => {
    resolverService = new RulesResolverService(/* dependencies */);
  });

  it('should evaluate rule sets', (done) => {
    const ruleSet = { condition: "or", rules: [{ field: "age", operator: ">", value: 18 }] };
    resolverService.evaluate(ruleSet).subscribe(result => {
      expect(result).toBe(true);
      done();
    });
  });
});

Conclusion

The Angular Rules Library provides a robust solution for parsing, resolving, and evaluating rules using dynamic data, nested conditions, and contextual workflows. It is suitable for applications requiring decision-making logic based on rules and conditions.

For contributions, feature requests, or bug reports, please reach out!

Clone this wiki locally